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

1
  • Are you looking for strlen()? Commented Nov 16, 2019 at 21:45

3 Answers 3

4
$str = "smartphones";

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

if (false !== strpos($str, $substr1)) {
    echo strlen($substr1); // same with other substrings
}
Sign up to request clarification or add additional context in comments.

Comments

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);
 }

Comments

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";}
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.