Find and Replace with Preg?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
User avatar
minimihi
php-forum GURU
php-forum GURU
Posts: 236
Joined: Sat Apr 14, 2012 11:57 am
Location: Vilnius, Lithuania

Sat May 19, 2012 1:40 am

If you have HTML string or string of URLs, you can use preg_replace, even thought simple str_replace() would be much easier.

1. You would be writing not unicode, but Regular Expression (regex for short). Follow previous link for tutorial, take your time to practicing it =D
2. Group subpaterns and use them to create new format. Subpaterns are separated by simple brackets.

simplest of simple sample ('cause that's all I'm capable of):

Code: Select all

$subject= '<a href="http://areallyspecificurl.com/watchID=12345dwad">1st</a>
<a href="http://areallyspecificurl.com/watchID=12347awawf">2nd</a>';
$pattern = '/(http:\/\/areallyspecificurl.com)\/(watchID=[0-9]+)/';
$replacement= '$1/username=jdoe&$2';
$returnValue = preg_replace($pattern, $replacement, $subject); 
Post Reply