0

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 5

1

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

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

4 Comments

what is the difference between strstr + strpos?
strstr returns the string starting from the first occurrence while strpos returns number (the position) of the substring
@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.
@Michael Robinson: Good explanation, but don't forget that third parameter in strstr is for PHP 5.3.0
1
if(strpos($big_string, $sub_string) !== false)
{
    // $big_string contains $sub_string
}

Comments

1

You could use strpos

if (strpos($haystack, $needle) !== false) {
    echo "the string '{$needle}' was found within '{$haystack}'";
}

Comments

1

You could use substr_count .. http://php.net/substr_count or strpos, http://php.net/strpos

1 Comment

thanks for providing the link, I tried google'ing it and found nothing
1

Either strpos() or stripos() (depending on whether you're interested in case sensitivity).

http://php.net/manual/en/function.strpos.php

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.