Page 1 of 1
PHP: testing whether a string contains another string.
Posted: Tue Apr 13, 2010 6:51 pm
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?
Re: PHP: testing whether a string contains another string.
Posted: Tue Apr 13, 2010 7:49 pm
by Falken
You should check out preg_match, a much better choice:
http://www.php.net/manual/en/function.preg-match.php
Re: PHP: testing whether a string contains another string.
Posted: Tue Apr 13, 2010 9:08 pm
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.
Re: PHP: testing whether a string contains another string.
Posted: Tue Apr 13, 2010 9:31 pm
by Age of Fable
Thanks for both these responses.