phpreplacecpu-wordblacklist

Wrap text in <span> tag after X number of words (not counting blacklisted words)


I'm looking for a PHP function to insert a <span> tag after the 2 first words on a string but ignore some number of words.

For example, ignore the words: One, Two, Three and add a <span> after the 2 next words.

//"ONE" IS IGNORED, SPAN ADDED ON THE NEXT 2 WORDS
$string = "One example text bla bla bla";
$output = "One example text <span>bla bla bla</spa>";

//String added after the second word
$string = "Another example text bla bla bla";
$output = "Another example <span>text bla bla bla</spa>";

Solution

  • It might seem longer but it is faster and highly configurable.

    Okay, so what you have to is find word delimiter, which in this case is space (" ").

    Next thing is to find 2 first words other than word from array e.g.: ("One","Two","Three",...).

    Third thing is to unit the array of words into some logical string.

    $string2Explode = "One great sentence is simply great."; //Also string
    $stringExploded = explode(" ",$string2Explode); //array([0] => "One", [1]=> "great" etc.);
    $preventedWords = array("One","Two","Three"); //Add prevented words here
    $stringImploded = "";
    $found = 0;
    $count = 0;
    while ($count !== count($stringExploded)) {
     $stringImploded .= $stringExploded[$count];
     if (!in_array($stringExploded[$count],$preventedWords)) {
      $found++;
     }
    
     $count++;
     if ((count($stringExploded)==$count)&&($found>=2)) {
      $stringImploded .= "</span>";
     } else {
        $stringImploded .= " ";
     }
      if ($found==2) {
       $stringImploded .= "<span>";
     }
    }
    
    //StringImploded also output.