php if character exists in string code example

Example 1: php find if string contains

if (strpos($string, 'substring') !== false) {
	// do stuff 
}

Example 2: php find if substring is in string

$result = strpos("haystack", "needle");

if ($result != false)
{
  // text found
}

Example 3: php check if string contains a char

$haystack = 'This is my haystack that we shall check'
$has_A = strpos($haystack, 'A') !== false;
$has_a = strpos($haystack, 'a') !== false;

Example 4: check if string contains character php

// this method is new with PHP 8 and above
$haystack = "Damn, I wonder if this string contains a comma.";
if (str_contains($haystack, ",")) {
	echo "There is a comma!!";
}

Tags:

Php Example