Replace only part of a match using preg_replace?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Replace only part of a match using preg_replace?

Post by Citizen »

Hey guys,

I researched a bunch and can't find the solution. Basically, I want to use preg_replace to find a string, and then replace *most* but not all of the string.

So, for instance, I tried this and it obviously doesn't work:

Code: Select all

<?
$patterns[] = '/<td class="menu" onclick="javascript&#058;window.location.href=\'(.*?)\';" onmouseover="this.className=\'menu2\';" onmouseout="this.className=\'menu\';">(.*?)<\/td>/';
$replacements[] = '<a id="12" href="(.*?)">(.*?)</a>';
 
$sHtml = preg_replace($patterns, $replacements, $sHtml);
?>
Any ideas?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Replace only part of a match using preg_replace?

Post by John Cartwright »

The replacement parameter contains each matched block, which can be accessed as $1, $2, and so forth.

Code: Select all

<a id="12" href="$1">$2</a>
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Re: Replace only part of a match using preg_replace?

Post by Citizen »

Thanks!

Why wouldn't they put that simpler in the documentation? :)
Post Reply