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?
PHP: testing whether a string contains another string.
-
Age of Fable
- Posts: 54
- Joined: Fri Feb 19, 2010 6:37 am
PHP: testing whether a string contains another string.
Easy to play - hard to survive. http://www.ageoffable.net
Re: PHP: testing whether a string contains another string.
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!
For all your game information needs!
Visit us at: http://www.gamedatabase.eu today!
- Jackolantern
- Posts: 10891
- Joined: Wed Jul 01, 2009 11:00 pm
Re: PHP: testing whether a string contains another string.
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.
The result of the above code is 35, since "right_here" begins at the 35th character in the haystack string.
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 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.
Thanks for both these responses.
Easy to play - hard to survive. http://www.ageoffable.net