Combine Combine - 1 year ago 77
PHP Question

PHP regex to convert span element into input

I have a question regarding PHP regexes.
How can one convert a text/string from the source format to a text/string like the target format? How can this be accomplished with php regex?

Source format:

What a <word>sily</word> <word>ting</word> love is!


Target format:

What a <input type="text" class="misspelled-word" value="sily"> <input type="text" class="misspelled-word" value="ting"> love is!


Thank you

Answer Source

It seems you don't even know the basics. Give a read to this and this to get a basic knowledge on how to use regular expressions in PHP.

Anyway, the replacement is really simple:

<?php
$string = 'What a <word>sily</word> <word>ting</word> love is!';
$pattern = '/<word>(\w+)<\/word>/';
$replacement = '<input type="text" class="misspelled-word" value="$1">';
echo preg_replace($pattern, $replacement, $string);
?>

See also a regex demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download