简体   繁体   中英

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.

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

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

This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM