PHP: testing whether a string contains another string.

Need help with an engine or coding not on the list? Need help with a game or the website and forums here? Direct all questions here.
Post Reply
Age of Fable
Posts: 54
Joined: Fri Feb 19, 2010 6:37 am

PHP: testing whether a string contains another string.

Post by Age of Fable »

I sometimes have to check whether a string contains a shorter string.

I've been doing this using str_replace, as follows:

if (str_replace("<B>","xxx",$longstring)<>$longstring) {

This would check whether $longstring contained '<B>'.

Is there a shorter way to do this?
Easy to play - hard to survive. http://www.ageoffable.net
Falken
Posts: 438
Joined: Fri May 08, 2009 8:03 pm

Re: PHP: testing whether a string contains another string.

Post by Falken »

You should check out preg_match, a much better choice: http://www.php.net/manual/en/function.preg-match.php
--- Game Database ---
For all your game information needs!
Visit us at: http://www.gamedatabase.eu today!
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: PHP: testing whether a string contains another string.

Post by Jackolantern »

Actually, unless you need the pattern-matching functionality of a regular expression, it is better to just use a simple string function for performance reasons. Of course regular expressions are much more powerful than simple string manipulation functions when you need them.

As far as finding a string in another string, you can use the strpos() function. strpos() can take two string parameters: the first being the string to search in (haystack), and the second being what you want to find (needle). If it finds the entire needle string in the haystack string, it returns a numeric value which represents the location of the first letter in the haystack string where the needle string was found. If the needle is not in the haystack, it will return false.

Code: Select all

$haystack = "this_is_some_words_to_look_through_right_here_and_that_is_all";
$needle = "right_here";

$result = strpos($haystack, $needle);

if ($result === false) {
      echo "The string was not found";
} else {
      echo "String '$needle' was found in string '$haystack' at position $result";
}
The result of the above code is 35, since "right_here" begins at the 35th character in the haystack string.
The indelible lord of tl;dr
Age of Fable
Posts: 54
Joined: Fri Feb 19, 2010 6:37 am

Re: PHP: testing whether a string contains another string.

Post by Age of Fable »

Thanks for both these responses.
Easy to play - hard to survive. http://www.ageoffable.net
Post Reply

Return to “Advanced Help and Support”