简体   繁体   中英

Regular expression help needed

Although I can find a lot of tutorials on regular expressions, it remains above my grasp. The regular expression that I want to create is simple (judged by what I see in some of the examples), but I simply can not figure it out.

I want to do a simple replacement as follows:

  1. I have image metadata saved in a MySQL table, with fields: id, name, title and alt.
  2. In my content, I want to write [[IMAGE:1:right]]content here[[image:2:left]].
  3. I want to get the matches of the ID (the digit) and the float (left or right) and replace the entire string with the image floated left or right, retrieved by the ID from the database table.

Here is my attempt:

preg_match("/^\[\[image:(\d+):(left|right)\]\]+/i", "[[IMAGE:1:right]]content here[[image:2:left]]", $matches);

This gives me the return of:

Array ( [0] => [[IMAGE:1:right]] [1] => 1 [2] => right )

So, it finds one, but I want it to find ALL of them, as I may have more than one image in a post. As far as I can tell, the + there should match all entries, and the i should match case insensitive. It appears as if the case insensitive way works, but I get only one return.

Could someone please let me know what I am doing wrong?

That's not quite how it works. That + only applies to the token immediately before it - the ] . You want to make the match global in Perl vernacular, which for PHP (which I think you're using?) means calling the function preg_match_all() . You'll also have to remove the ^ , as only one of the images occurs at the beginning of the string.

Also, [ and ] are special characters in regex - so please escape them when you want a literal bracket by writing \\[\\[ and \\]\\] .

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