Reputation: 1460
So I'm admittedly miserable with regular expressions, so if someone could help me out a bit here both in respect to figuring out how I can perform a particular search; but also how the applied regular expression actually works, I'd be ecstatic.
I'm trying to achieve placement/replacement of a 'user modifiable tag' in a PHP framework I'm building up.
The example is as follows:
$ReplacementOpenTag = "[{";
$ReplacementCloseTag = "}]";
$SomeRegex = "$ReplacementOpenTag(...)$ReplacementCloseTag";
$Matches = array();
if( preg_match_all($ReplacementSubject,$SomeRegex,&$Matches) <= 0 )
return;
else
foreach( $Matches as $Match ) // <--- Match?
echo($Match[0]); // <--- Right?
Where the user would be able to set the Open and Close tag to say - "<{" or "[|" if so inclined - in case for some reason my 'standard' tags aren't suitable to their needs.
Now... I feel like this seems way too easy - but after some time fumbling around at http://tryphpregex.com/ and coming up short, repeatedly, I figure it's time to see if I can get a quick and easy solution to this presumably easy regex so that I can dissect it and figure out what I'm missing.
I feel like there should be a 'Stupid-Question' tag...
Upvotes: 1
Views: 52
Reputation: 51330
First, escape your delimiters, because they may contain special characters (and in your example, they do):
$ReplacementOpenTag = preg_quote($ReplacementOpenTag);
$ReplacementCloseTag = preg_quote($ReplacementCloseTag);
Next, build a regex, using a nongreedy pattern in between the delimiters:
$SomeRegex = "/$ReplacementOpenTag(.*?)$ReplacementCloseTag/s";
Then, just use it like this
preg_match_all($SomeRegex, $ReplacementSubject, $Matches);
Or, for the replacement:
preg_replace($SomeRegex, "<b>$1</b>", $ReplacementSubject);
Upvotes: 1