PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How can I combine two (or more) preg_replace's - PHP

 November 20, 2022     bbcode, php, preg-replace, regex     No comments   

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 or url
  • \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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing