Jump to content

Problem with my preg_replace


Davikore

Recommended Posts

Hi,

 

I am trying to replace an image inside an html  file using this:

 

The file contains this:

 

<img class="uiProfilePhoto headerTinymanPhoto uiProfilePhotoLarge img" src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/370282_100003830116243_1299179951_q.jpg" alt="" />

 

And I want to replace it with this:

 

<img class="uiProfilePhoto headerTinymanPhoto uiProfilePhotoLarge img" src="http://example.com/FC.jpg" alt="" />

 

This is what I have tried:

 

$URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";

$page_html = preg_replace("#headerTinymanPhoto uiProfilePhotoLarge img\" src=\"($URLSearchString)\"#", 'http://example.com/FC.jpg', $page_html);  

 

But its not working. :confused:

 

Can anyone see what I have done wrong ?

 

Is preg_replace the correct tool to use ?

 

Thanks.

 

 

 

.

Link to comment
https://forums.phpfreaks.com/topic/262240-problem-with-my-preg_replace/
Share on other sites

Your search string is looking for the literal string " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'" - NOT those characters. You could put those characters in a character class to do what you intended [ a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\], but there is a much better way. Use a negative character class to look for any characters that are not a double quote. Also you should also "capture" the text before the replacement so you can put it back in. Otherwise you will lose the class parameter text (unless you were to hard code it in the replacement).

 

$pattern = '#(headerTinymanPhoto uiProfilePhotoLarge img" src=")([^"]*)#';
$replacement = '${1}http://example.com/FC.jpg';

$page_html = preg_replace($pattern, $replacement, $page_html);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.