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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.