1

Here is the function

function replaceclass($html) {
    return preg_replace_callback('/class="([^"]+)"/', function($m) {

    if(strpos($m[1], "container") !== false) {
        $m[0] = preg_replace("/\s*container\s*/",'product-description-table',$m[0],1);
        }

    if(strpos($m[1], "content-border") !== false) {
    $m[0] = preg_replace("/\s*content-border\s*/",'product-content-border',$m[0],1);
        }

// add as many if conditions with class replacement names as you like
// if(strpos($m[1], "class-name") !== false) {
//     $m[0] = preg_replace("/\s*class-name\s*/",'new-class-name',$m[0],1);
//      }
// add as many if conditions with class replacement names as you like

    return $m[0];

       }, $html);
}

This is working great on classes with only one class in them

Before

<table class="container">

After

<table class="product-description-table">

But whenever an element has more than one class, the following format error occurs

Before

<table class="container c8">

After

<table class="product-description-tablec8">

Can anyone think of an easy way to amend this function to detect secondary classes and add the appropriate spacing, <table class="product-description-table c8">?

1 Answer 1

2

The problem is that you're removing all the whitespace around the class with the \s* patterns in the regexp.

Instead of matching whitespace, use \b to match word boundaries.

    $m[0] = preg_replace("/\bcontainer\b/",'product-description-table',$m[0],1);
Sign up to request clarification or add additional context in comments.

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.