I have variable x and I want to see if it contains a string like hs even though the value may be cug hs ib ap. Can anybody help me figure this out? Thanks!
5 Answers
PHP strstr
<?php
$x = 'cug hs ib';
$y = strstr($x, 'hs');
echo $y;
?>
Update: Better user strpos
<?php
$x = 'cug hs ib';
$y = strpos($x, 'hs');
if($y === false)
// Not a substring
else
// Substring
?>
4 Comments
Joe Torraca
what is the difference between strstr + strpos?
SlavaNov
strstr returns the string starting from the first occurrence while strpos returns number (the position) of the substring
Michael Robinson
@JosephTorraca:
strstr finds the first occurrence of a substring within a string, returning the string from that index unless the third parameter is set to true. strpos returns the index of the first character of the first occurrence of a substring or false if not found.SlavaNov
@Michael Robinson: Good explanation, but don't forget that third parameter in strstr is for PHP 5.3.0
You could use strpos
if (strpos($haystack, $needle) !== false) {
echo "the string '{$needle}' was found within '{$haystack}'";
}
Comments
1 Comment
Joe Torraca
thanks for providing the link, I tried google'ing it and found nothing
Either strpos() or stripos() (depending on whether you're interested in case sensitivity).