Skip to content
Advertisement

How to use str_replace in PHP so it doesn’t effect html tags and attributes

I want to change some words (random word leaving first and last word) in page in WordPress . For example Team will be Taem, Blame will be Bamle. I am using str_replace to acheive this with the_content filter

function replace_text_wps($text){
         
$textr=wp_filter_nohtml_kses( $text );
$rtext= (explode(" ",$textr));
$rep=array();
foreach($rtext as $r)
{
    //echo $r;
    if (strlen($r)>3)
    { 
        if(ctype_alpha($r)){
        $first=substr($r,0,1);
     $last=substr($r,-1);
     $middle=substr($r,1,-1);
     
    $rep[$r]=$first.str_shuffle($middle).$last;
        }
    }
 }

$text = str_replace(array_keys($rep), $rep, $text);

return $text;
}

add_filter('the_content', 'replace_text_wps',99);

The issue I am facing is when I run str_replace it also changes text in links and classes of HTML. I just want to change the text not html. For example if I change Content word
<a class='elementor content'>Content Here</a> It becomes <a class='elementor conentt'>Conentt Here</a

Can someone provide a Good solution for this?

Advertisement

Answer

If you realy have to use str_replace

Use preg_split to split between HTML tags and plain text:

function my_text_filter($text) {
    $out = "";
    $parts = preg_split('/(<[^>]+>)/', $text, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    foreach ($parts as $part) {
        if ($part && '<' === $part[0] && '>' === substr($part, -1)) {
            $out .= $part; // Is a HTML tag, skip!
            continue;
        }
        $out .= replace_text_wps($part);
    }
    return $out;
}

add_filter('the_content', 'my_text_filter', 99);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement