2

how i can check a value in PHP string that it's exists or not while when is use strpos() function then i face a problem when i check in a string suppose i have a string I m a Programmer then if i check Pro then strpos show its index value

<?php
$string="I m Programmer";
$found="Prog";
echo strpos($string,$found);
?>

strpos() show Porg index value while i want if Prog word exists in string then show index value if its not then should be show nothing because i want match Programmer work fully not Prog

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

4 Answers4

3

You can do by using pre_match() function, due to i it'll ignore case sensitive. for more detail you can read the pre_match documents here. pre_match

<?php
// for insensitive string
function insensitive($val,$str){
    if(preg_match("/\b$val\b/i",$str) ){
      return 1;
    }else{
      return 0;
    }
}
// for case sensitive string
function sensitive($val,$str){
    if(preg_match("/\b$val\b/",$str) ){
      return 1;
    }else{
      return 0;
    }
}
$string = 'I m programmer'; 
$found="Programmer"; 

// call function like this to get result
echo insensitive($found,$string);
echo sensitive($found,$string);
?>
Arslan
  • 46
  • 2
2

Try -

$string = 'I m Programmer'; //  "I m Programmer." - will work too
$found="programmer"; // lower case
echo preg_match("/\b$found\b/i",$string) ? 'Matched' : 'No Match';

i modifier for insensitive. Case insensitive match

preg_match()

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

You can use PHP preg_match

<?php
$string = 'I m Programmer';
$found="Prog";
if ( preg_match("~\b$found\b~",$string) ){
    echo "Matched";
}else{
   echo "No Match";
}
?>

Not case sensitive :

if ( preg_match("~\b".strtolower($found)."\b~",strtolower($string)) ){
    echo "Matched";
}else{
   echo "No Match";
}
SirMissAlot
  • 120
  • 2
  • 11
0

You also can use strpos, just check the char after the searched if is in a~z.

$str = strtolower($str);
$search = strtolower($search);
$is_in = (false !== ($pos = strpos($str,$search))) && !in_array($str[$pos + strlen($search)],['a','b','c',...'z']);
LF00
  • 27,015
  • 29
  • 156
  • 295