0

Can I have a detail explain about how can I replace with tag with current attr using php?

I read manual and some referencs

How to use php preg_replace to replace HTML tags

For the easy command I can understand, but for the search command on preg_replace with letters like ~, $1, /n, and etc, I dont understand at all...

If I want to replace

 <script src="core.js"></script>

into

 <temp src="library/js/core.js"></temp>

How can I implement preg_replace?

Thank you very much for your advice.

2 Answers 2

1

You need to learn about regular expressions, this site is a useful resource;

A quick example with preg_replace could be something like this - it could be improved, but hopefully will give you the idea...

<?php
$string = '<script src="core.js"></script>';
$pattern = '/<script src\s?=\s?['|"](.*)['|"]><\/script>/i';
$replace = ' <temp src="library/js/$1"></temp>';
$result = echo preg_replace($pattern, $replace, $string);
?>

You will need to learn about back-references in order to use matched bits of the string to create your new one. Briefly, the part of your pattern that is wrapped in parenthesis can be retrieved later with the $1 token which you include in your $replace string. You can back-reference as many times as you want this way. You can test regular expressions as you are working on them here too, hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!. I will take look at these sites now
1

It is almost never a good idea to use regular expressions for HTML. Consider DOM, then something like:

foreach($dom->getElementsByTagName('script') as $script) {
    $temp = $dom->createElement('temp');
    /*
     * create src attribute, append it to $temp and copy value from $script
     * I leave that up to you.
     */
    $script->parentNode->replaceChild($temp, $script);
}

1 Comment

I am using tidy...so I dont need to get $html from $dom..I only need to know how to use preg_replace

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.