Maxi-Pedia Forum

Information Technologies and Systems (IT/IS) => Other, SEO: Feel free to build your links here => Topic started by: atari on October 20, 2008, 01:31:12 pm



Title: How to find a string inside other string
Post by: atari on October 20, 2008, 01:31:12 pm
Looking for a function in PHP or some way to find out if a string contains some other string.


Title: PHP Check for string inside a string
Post by: mod on October 22, 2008, 05:33:10 pm
Let's say you have string $haystack = "mother" and string $needle = "other".

You want to find out if $haystack contains $needle.

One option is to use the strpos PHP function.

Code:
$pos = strpos($haystack,$needle);

if($pos === false) {
// string needle NOT found in haystack
}
else {
// string needle found in haystack
}

!! Watch out, this can be tricky. Some people do just something like if ($pos > 0) {} or perhaps something like if (strpos($haystack,$needle)) { } and forget that your string can be right at the beginning. if (strpos($haystack,$needle)) { } does not produce the same result as our code shown above.

Another option is to use strstr

Code:
if (strlen(strstr($haystack,$needle))>0) { echo "Needle Found"; }

Strstr function is case-sensitive. For a case-insensitive search, use stristr().
The strpos() function is faster and less memory intensive.


Title: Re: How to find a string inside other string
Post by: bugibar on October 30, 2008, 08:48:27 pm
I would include some checking for the string being empty too, maybe something like

Code:
<?php
function isempty($var) {
    if (((
is_null($var) || rtrim($var) == "") && $var !== false) || (is_array($var) && empty($var))) {
        echo 
"yes<br />";
    } else {
        echo 
"no<br />";
    }
}
?>