1

I need a function in php that will work in this way.

$string = "blabla/store/home/blahblah";

If in $string you find /store/ then do this, else do that.

How can I do it?

Thanks!

5 Answers 5

4

you're looking for strpos() function

Sign up to request clarification or add additional context in comments.

1 Comment

if(strpos($string, "/store/") !== false) { do_something(); }
3
$string = "blabla/store/home/blahblah";
if (preg_match("|/store/|", $string)){
    //do this
}
else{
    //do that
}

or

$string = "blabla/store/home/blahblah";
if (false !== strpos($string, "/store")){
   //do this
}
else{
    //do that
}

4 Comments

this is discouraged by documentation. Prefer strpos() : "Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."
In this particular example, using strpos() is better because it accomplishes the same thing and is faster than a regex.
strpos can return 0 meaning "I found it at the very beginning", but 0 is falsy and your if statement will lead to an incorrect result.
+1 for giving nice examples, but as the PHP-doc states: "Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."
2
if (strpos($string, "/store/") !== false) {
    // found
} else {
    // not found
}

Comments

1

Try using the strrpos function

e.g.

$pos = strrpos($yourstring, "b");
if ($pos === true) { // note: three equal signs
//string found...
}

Comments

1

Seems like you're looking for the stristr() function.

$string = "blabla/store/home/blahblah";
if(stristr($string, "/store/")) { do_something(); }

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.