Phoenix
Phoenix

Reputation: 1075

about php str_replace function

Here is my code:

$search = array('<script src="/',
        '<link href="/',
        '<a href="/',
        '<img src="/',
        'src="/');
$d = 'http://www.ifreewind.net';
$replace = array('<script src="'.$d.'/',
         '<link href="'.$d.'/',
         '<a href="'.$d.'/',
         '<img src="'.$d.'/',
         'src="'.$d.'/');
$result = str_replace($search, $replace, $contents);

echo $result;

These code have a problem is that they cannot replace img tag such as :

<img width="50px" src="/..."> 

into

<img width="50px" src="http://www.ifreewind.net/...">

How to fix that?

Upvotes: 0

Views: 195

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 220056

You can't use str_replace for this. You could try it with preg_replace:

preg_replace('~(src|href)="(?=/)~', '$1http://www.ifreewind.net', $contents);

However, I'd strongly advise you to use an HTML parser instead.

Upvotes: 1

Related Questions