0

In PHP i'm trying to cut out a specific word with the substr function.

The way I am doin this is:

  • Check if the word actually exists in the string:

    $haystack = "/home/{i:id}/{s:aString}";
    $needle = "{i:id}";
    
    if ($position = strpos($haystack, $needle)) {...}
    
  • Calculate the last character in the word by using substr

    $haystack = "/home/{i:id}/{s:aString}";
    $needle = "{i:id}";
    
    if ($position = strpos($haystack, $needle)) {
       $rpos = strpos($haystack, substr($needle, -1), $position);
       ...
    }
    
  • Print out the word by using substr again

    $haystack = "/home/{i:id}/{s:aString}";
    $needle = "{i:id}";
    
    if ($position = strpos($haystack, $needle)) {
       $rpos = strpos($haystack, substr($needle, -1), $position);
    
       echo substr($haystack, $position, $rpos);
    }
    

When running this piece of code, it strips the whole word, but stops way to late, it also takes 5 characters of the remainder of the string.

How do I fix this substr so it will only take the word i'm looking for?

Bas
  • 2,106
  • 5
  • 21
  • 59

1 Answers1

0

I'm not having enough reputation so posting answer. Try this,

<?php
$sentence  = "I want to remove all the common words from this sentence because they are irrelevant";
$common_words = array("to ", "this ", "all ", "the ", "from ");

$newphrase = str_replace($common_words, "", $sentence);
echo "Actual Word : ".$sentence."\n\nNew Word : ".$newphrase;
?>

Let me know if it helps.

  • please have a look at http://php.net/manual/en/function.str-replace.php it might help to improve your answer. – Evhz Jul 20 '16 at 10:37