Joe Torraca
Joe Torraca

Reputation: 2018

PHP check for string inside string

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!

Upvotes: 0

Views: 120

Answers (5)

Ben D
Ben D

Reputation: 14489

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

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

Upvotes: 1

user862010
user862010

Reputation:

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

Upvotes: 1

Michael Robinson
Michael Robinson

Reputation: 29508

You could use strpos

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

Upvotes: 1

user142162
user142162

Reputation:

if(strpos($big_string, $sub_string) !== false)
{
    // $big_string contains $sub_string
}

Upvotes: 1

SlavaNov
SlavaNov

Reputation: 2485

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

?>

Upvotes: 1

Related Questions