0

Does anyone know how can I do a string check inside a string?

for example:

$variable = "Pensioner (other)";

If I want to check whether $variable contain the word 'Pensioner', how can I do it in PHP? I have tried the following code in php, but it's always return me false :(

$pos = strripos($variable,"Pensioner");
if($pos) echo "found one";
else echo "not found";

4 Answers 4

3

In the manual, the example uses a === for comparison. The === operator also compares the type of both operands. To check for 'not equal', use !==.

Your search target 'Pensioner' is at position 0, and the function returns 0, which equal false, hence if ($pos) failed all the time. To correct that, your code should read:

$pos = strripos($variable,"Pensioner");
if($pos !== false) echo "found one";
      else echo "not found";
Sign up to request clarification or add additional context in comments.

Comments

2

Update:

You are using the reverse function strripos, you need to use stripos.

if (stripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}

This should do:

if (strripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}

The strict type comparison (!==) is important there when using strpos/stripos.

1 Comment

yes, I do tried using your provided code, but the result still the same, it will not show me the correct answer
1

The problem with strripos and its siblings is that they return the position of the substring found. So if the substring you're searching happens to be at the start, it returns 0 which in a boolean test is false.

Use:

if ( $pos !== FALSE ) ...

Comments

1
$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');

if ($pos !== FALSE) {
 echo 'found one';
} else {
 echo 'not found';
}

^ Works for me. Note that strripos() is case insensitive. If you wanted it to be a case-sensitive search, use strrpos() instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.