简体   繁体   中英

How can I find a 'user defined tag' using a regular expression?

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...

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);

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