0

I have a string and three sub strings:

$str = "smartphones";

$substr1 = "smart";
$substr2 = "phon";
$substr3 = "smartphone";

running the three substrings through a function should return 5, 4 and 10 respectively. If there's no match, it should return 0.

EDIT:

Also, if the string is "smartphones and other phones", $substr2 should still return 4, not 8

nick
  • 2,819
  • 5
  • 33
  • 69

3 Answers3

4
$str = "smartphones";

$substr1 = "smart";
$substr2 = "phon";
$substr3 = "smartphone";

if (false !== strpos($str, $substr1)) {
    echo strlen($substr1); // same with other substrings
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

You can use strpos() function to find the first occurrence of the substr and then just return the length of the substr.

function substrMatched($str, $substr){
    $res = strpos($str, $substr);
    if($res === false)
        return 0;
    return strlen($substr);
 }
0

Well, given Answer above was not exactly what you wanted :) I'd solve it like that:

    //Code snipplet with iteration

    $str = "smartphones phone";

    $substr1 = "smart";
    $substr2 = "phon";
    $substr3 = "smartphone";

    $substr_array[] = $substr1;
    $substr_array[] = $substr2;
    $substr_array[] = $substr3;


     foreach ($substr_array as $substr) {
       if($str[strpos($str,$substr,0)]!= " "){
       echo substr_count($str,$substr). " at Position";
       echo strpos($str,$substr,0). "\xA";}
      }
mZed
  • 339
  • 2
  • 7