|
Posted by Ian Hobson on 09/05/07 20:39
Peter wrote:
> Hi,
>
> I parse some text an make alterations. The text is machine generated and
> always the same in syntax and layout, so that makes things a bit easier.
> One of the alterations is that I want to remove the WIDTH and HEIGHT from
> <IMG> data. So that I can easily change images on the server (different
> sizes) without having to alter the html again.
>
> Following works for me:
>
> $help_body = preg_replace ("/WIDTH=\"(.*)\" HEIGHT=\"(.*)\" BORDER=\"0\"/",
> " BORDER=\"0\"", $help_body);
>
> BUT ... I just noticed that it doesn't work when there are two images
> sitting next to each other on the same line.
> The reason seems to be that the preg_replace finds as much as possible
> between 'HEIGHT' and 'BORDER', inclusive another 'HEIGHT' and 'BORDER' on
> the same line.
> How do I manipulate it so that the preg_replace works for both <IMG>
> instances on the same line ?
>
Hi Peter,
1) The width and height (and border) all have digits between the quotes,
yet your pattern has dots. Dot matches any character except newline,
which is why your expression matched too much.
2) You state you want to change <IMG tags, but your code changes
anything with WIDTH and HEIGHT and BORDER. Only you can confirm these
are the same.
3) You match more than required, and then put it back again...
Therefore I would do something like this
$pattern = "<IMG /WIDTH\"(\d*)\" HEIGHT=\"(\d*)\"";
$replace = "<IMG";
$help_body = preg_replace($pattern,$replace,$help_body);
I note that you mention alterations in the plural. Both $pattern and
$replace can be arrays, and preg_replace will perform all changes at
once rather efficiently.
Regards
Ian
Navigation:
[Reply to this message]
|