Welcome to Maxi-Pedia Forum. Maxi-Pedia discussion forum is a free community inviting you to express your ideas and discuss various topics with other contributors.

December 06, 2021, 06:18:58 am *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register  
Most Recent Posts:
Pages: [1]
  Print  
Author
Topic: 

How to find a string inside other string

 (Read 6489 times)
atari
Full Member
***
Posts: 121


« 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.
Logged
Maxi-Pedia Forum
« on: October 20, 2008, 01:31:12 pm »

 Logged
mod
Moderator
*****
Posts: 525


« Reply #1 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.
« Last Edit: October 23, 2008, 10:50:33 am by mod » Logged
bugibar
Full Member
***
Posts: 107


« Reply #2 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 />";
    }
}
?>
Logged
Maxi-Pedia Forum
   

 Logged
Pages: [1]
  Print  
 
Jump to:  

Page created in 0.085 seconds with 23 queries. (Pretty URLs adds 0.001s, 0q)