Str_replace spaces with hyphens in tag name attribute A

$ string = preg_replace ("# [name = ([a-zA-Z0-9.-] +) *] #", ''. "$ 1", $ string);

This part of the script doesn't work:

str_replace(' ', '-', "$1")

      

I need to replace "with" - " , I will also try preg_replace

inside the main one preg_replace

, str_ireplace

also

But it still doesn't work

+2


source to share


2 answers


Replacement is assessed in advance, not on each replacement. But you can do it either with a modifier e

in your regex
:

$string = preg_replace("#\[name=([a-zA-Z0-9 .-]+)*]#e", '"<td><a href=\"$front_page/".str_replace(" ", "-", "$1")."\">$1</a></td>"', $string);

      



Or using preg_replace_callback

:

function callbackFunction($match) {
    global $front_page;
    return '<td><a href="'.$front_page.'/'.str_replace(" ", "-", $match[1]).'">'.$match[1].'</a></td>';
}
$string = preg_replace_callback("#\[name=([a-zA-Z0-9 .-]+)*]#", 'callbackFunction', $string);

      

+5


source


I think you will have to do it in two steps as $1

it cannot be used in str_replace()

. $1

doesn't really exist as a variable, it is only a placeholder in the replacement string.



+1


source







All Articles