PHP check if string contains something

Checking if a string contains a substring is very frequently occuring use case in PHP code. PHP functions strpos or stripos (case insensitive version) can be used for this. Here are some examples.

strpos example

<?php
$str = "Hello world";
$pos = strpos($str, "world");
if ($pos !== FALSE) {
  echo "FOUND at post:$pos\n";
} else {
  echo "NOT_FOUND\n";
}
?>
FOUND at post:6
Env: PHP 5.5.9 (Linux)

stripos example

<?php
$str = "Hello world";
$pos = strpos($str, "WORLD");
if ($pos !== FALSE) {
  echo "strpos: FOUND at post:$pos\n";
} else {
  echo "strpos: NOT_FOUND\n";
}
$pos = stripos($str, "WORLD");
if ($pos !== FALSE) {
  echo "stripos: FOUND at post:$pos\n";
} else {
  echo "stripos: NOT_FOUND\n";
}
?>
strpos: NOT_FOUND
stripos: FOUND at post:6
Env: PHP 5.5.9 (Linux)
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments