How to check a string contains substring in php?
The function will check a string contains substring, the string to be checked may contain underscores.
1. Code:
<?php function checkContainsSubstringWithUnderscore($str, $substr){ $hayStack = strtolower((string)$str); $needle = strtolower((string)$substr); $pos = strpos($str,$substr); $matchItemName = true; $isPass1 = true; $isPass2 = true; if($pos === false){ $isPass1 = false; } $needle = str_replace("_"," ",$substr); $pos = strpos($str,$substr); if($pos === false){ $isPass2 = false; } if(!$isPass1 && !$isPass2){ $matchItemName = false; } return $matchItemName; } $str = "Soltuts.com is providing PHP tutorials"; $substr = "Soltuts.com"; var_dump(checkContainsSubstringWithUnderscore($str, $substr)); ?>
2. Example:
Input:
$str = "Soltuts.com is providing PHP tutorials"; $substr = "Soltuts.com"; $substr1 = "PHP_tutorials"; checkContainsSubstringWithUnderscore($str, $substr); checkContainsSubstringWithUnderscore($str, $substr1);
Output:
bool(true) bool(true)