简体   繁体   中英

Replace substring with an elaboration of $1 in PHP

I have a text containing pseudo-tags, used as placemarks to indicate the presence of HTML elements (ie a photogallery).

some text <gallery src="img/myfolder" /> some other text...

My goal is to replace all the occurences of <gallery> with an HTML code displaying a photogallery of images included in "img/myfolder".

I've found in this answer . Unfortunately I can't perform the direct replacement as indicated there, because I need to do some elaboration before. I must take the "img/myfolder" substring extracted from the text, do a folder scan (I already have the code to perform it) and finally replace <gallery> with something like this

<ul>
<li><img src="img/myfolder/image1.jpg" /></li>
<li><img src="img/myfolder/image2.jpg" /></li>
<li><img src="img/myfolder/image3.jpg" /></li>
</ul>

where images are extracted from "img/myfolder" scan and are unknown when I invoke the preg_replace call. How can I do? Is there an efficient way to perform my goal? Thanks in advance.

In a word:

preg_replace_callback()

This function allows you to do some sophisticated substitutions. There is an easy guide here: preg_replace_callback

Overview of the Procedure

A. Step 1: You need to match

<gallery src="img/myfolder" />

Build a regex pattern $regex that matches the whole string and places the path ("img/folder") in Group 1.

For instance:

$regex = '%<gallery src="([^"]+)" />%';

B. Call preg_replace_callback and pass it $regex , "replaceGallery" and $string

$new = preg_replace_callback($regex,"replaceGallery",$string);

replaceGallery($m) will be your callback function. It will build the intricate substitution you are trying to do.

Now define the function replaceGallery($m) . Do not worry about $m , this is the parameter that preg_replace_callback will automatically pass to the function. Just remember that $m[0] will be the whole match. $m[1] will be the folder path.

Knowing the folder path $m[1] , you can go lookup all the images in the folder. Then you can build your string.

Then return your string.

function replaceGallery($m) {
   // Your code here
   // use $m[0] and $m[1]
   return $gallery; 
   }

Using $gallery , preg_replace_callback will replace the entire match with the string you built.

A beautiful function, isn't it?

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