Search code examples
phpstringstr-replace

Ignore HTML with str_replace


I'm trying to replace spaces with an underscore (_) with str_replace but it also affects HTML tags.

My code:

add_filter( 'facetwp_facet_html', function( $output, $params ) {
    if ( 'blog_tags' == $params['facet']['name'] ) {
        $output = str_replace(' ', '_', $output);
    }
    return $output;
}, 10, 2 );

The expected result was:

<div class="checkbox">Dynamic_String_Exemple<span class="counter">1</span></div>

but it returns:

<div_class="checkbox">Dynamic_String_Exemple<span_class="counter">1</span></div>

div_class span_class

What's the best way to prevent this?


Solution

  • We only have one sample string to build from, so I make no guarantees that this will work for all cases in your project, but...

    You should use a dom parsing technique because basic string function targeting will be more error prone in valid html.

    Code: (Demo)

    $html = <<<HTML
    <div class="checkbox">Dynamic_String_Exemple<span class="counter">1</span></div>
    HTML;
    
    $dom = new DOMDocument;
    $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $firstDivFirstNode = $dom->getElementsByTagName('div')->item(0)->childNodes->item(0);
    $firstDivFirstNode->nodeValue = str_replace(' ', '_', $firstDivFirstNode->nodeValue);
    echo trim($dom->saveHTML());