vorobey
vorobey

Reputation: 4521

str_replace spaces with hyphens in A tag's name attribute

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

This part of script doesn't work:

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

I need to replace " " with "-", i also try preg_replace inside main preg_replace, str_ireplace also

But this is still don't working

Upvotes: 2

Views: 562

Answers (2)

igor
igor

Reputation: 2100

I guess you will have to do it in two steps, since $1 cannot be used in str_replace(). $1 doesn’t really exist as a variable, it is only a placeholder in the replacement string.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655559

The replacement is evaluated upfront and not on each replace. But you can do so by either using the e modifier in your regular expression:

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

Or by 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);

Upvotes: 5

Related Questions