开发者

how do I say "If a string contains "x" in PHP?

开发者 https://www.devze.com 2023-03-16 01:10 出处:网络
I have a variable: $testingAllDay = $event->when[0]->startTime; This variable will be this format if it is \"All Day\":

I have a variable:

$testingAllDay = $event->when[0]->startTime;

This variable will be this format if it is "All Day":

2011-06-30

It will be this format if it is not "All Day":

2011-07-08T12:00:00.000-05:00

I'm wanting to do something like:

if ($testingAllDay does not co开发者_如何学Gontain "T"){
   $AllDay = 1;
   } else {
   $AllDay = 0;
}

Do I need to use a strstr() here, or is there another function that does this? Thanks!


One option is to use strpos to see if the 'T' character is present in the string as follows:

if (strpos($testingAllDay, 'T') !== false) {
    // 'T' was present in $testingAllDay
}

That said, it would probably be faster/more efficient (although no doubt meaninglessly so) to use strlen in this case, as according to your example, the time-free field will always be 10 characters long.

For example:

if(strlen($testingAllDay) > 10) {
    // 'T' was present in $testingAllDay
}


Use strpos:

if (strpos($testingAllDay,"T")!==false){

or strstr

if (!strstr($testingAllDay,"T")){


if (strpos($testingAllDay, 'T') !== FALSE){
   ...
}


If those are the only possible cases, even strlen() will do.


not exactly answer to the question, but you could check with strlen(). i.e. "All Day" length is 10, anything above that is not.


The function you're looking for is strpos(). The following is an example picking up your wording for the variable names even:

$testingAllDayTPosition = strpos($testingAllDay, 'T');

$testingAllDayDoesNotContainT = false === $testingAllDayTPosition;

if ($testingAllDayDoesNotContainT){
   $AllDay = 1;
   } else {
   $AllDay = 0;
}


strstr and strpos are two functions by which you can complete your requirement.

strstr will see if substring exists in string and it will echo from first occurrence of string to rest.

While strpos will give you position of first occurrence of the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消