Issue
< EDIT >
I Wanted to give a big thank you to all of you who have provided an answer, You have all given me great options. I will play with each and see which one suits my exact needs prior to selecting an answer. I do appreciate all of your responses though, everyone has a different approach to things. =)
bbcodes can (but not always do) include options, an example would be:
[URL="http://google.com"]GOOGLE[/URL]
</ EDIT >
I am currently hiding multiple variables from my string using the following method:
$result = preg_replace('/\[img\](.*)\[\/img\]/im', 'REPLACED', $qry);
$result = preg_replace('/\[url.*\](.*)\[\/url\]/im', 'REPLACED', $qry);
This works, but I would like to be able to do this with just one preg replace, and easily be able to add to it in the future if needed.
I have attempted to use:
$result = preg_replace("#\[/?(img|url)(=\s*\"?.*?\"?\s*)?]#im", 'REPLACED', $qry);
Which is only hiding the tags themselves.
How can I combine these replaces?
Solution
You can use
preg_replace('~\[(img|url)\b[^]]*](.*?)\[/\1]~is', 'REPLACED', $qry);
The regex matches:
\[
- a[
char(img|url)
- Group 1:img
orurl
\b
- a word boundary[^]]*
- 0 or more chars other than]
]
- a]
char(.*?)
- Group 2: any zero or more chars, as few as possible\[/\1]
-[/
, the same contents as in Group 1, and a]
.
See the PHP demo:
$qry = '[url="google.com"]google[/url] and [img]image here[/img]';
echo preg_replace('~\[(img|url)\b[^]]*](.*?)\[/\1]~is', 'REPLACED', $qry);
// => REPLACED and REPLACED
Answered By - Wiktor Stribiżew Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.