user1184908
user1184908

Reputation: 45

preg_replace how to do that?

So I occured one problem. I got a code -

[caption id="attachment222" align="aligncenter" width="520" caption="caption ghoes here"]<img class="image-caption" title="title" src="picture link goes here" alt="" width="520" height="328" />[/caption]

So basically what I need to do is go through $content, get each <img> src that is inside [caption][/caption] tags, for more info, see the code above, and insert the src link inside caption and remove the img tag, so in the end it would look like [caption id="attachment222" align="aligncenter" width="520" caption="caption ghoes here" url="picture link goes here"][/caption] .

AS you can see, the src is changed to url too. Hope you can help me with this.

Upvotes: 0

Views: 128

Answers (3)

bummzack
bummzack

Reputation: 5875

This should work:

$parsed = preg_replace(
    '{\[caption([^\]]+)\]<img.*?src=["\'](.*?)["\'].*?/>}mi',
    '[caption$1 url="$2"]',
    $sourceText
);

Upvotes: 0

thenetimp
thenetimp

Reputation: 9820

This isn't exact, but it will point you in the right direction.

Using a regexpression like this will do 2 things get your caption data, and your image src

[caption (.*)]<img class="image-caption" title="title" src="(.*)" alt="" width="520" height="328" />[/caption]

Then you use it in preg_replace with this.

[caption $1 src="$2"][/caption]

$1 is the content in (.) of your caption and $2 is the image src. If the title and other attributes in the [img] tag are dynamic then simply replace them in the reg express with . like so.

[caption (.*)]<img class=".*" title=".*" src="(.*)" alt=".*" width=".*" height=".*" />[/caption]

That should work. (I suck at regular expressions, so there may be a more elegant way).

Upvotes: 1

Zenexer
Zenexer

Reputation: 19613

Your regex might be something like #<img.*?/>#i. I'll let you figure out the rest.

Upvotes: 0

Related Questions