Home > OS >  How to check if string contains part of string (not whole string) in PHP
How to check if string contains part of string (not whole string) in PHP

Time:12-15

I have problem with checking if part of string is containing other string but strpos and stripos are not working for me.

The case that I need to check if word pris is containing in string -med prista-

Any suggestions?

CodePudding user response:

Try

$str = '-med prista-';
if (preg_match('/pris/', $str))
    echo 'OK';
else
    echo 'Not';

CodePudding user response:

In PHP 8 you have a new function called str_contains() created for this purpose:

if (str_contains('-med prista-', 'pris')) {
    echo "Found!";
}

If you are using older PHP versions then you can use mb_strpos (multibyte), or strpos functions like this:

if(mb_strpos('-med prista-', 'pris') === false){
    // not found
} else {
    echo "Found!";
}
  •  Tags:  
  • php
  • Related