简体   繁体   中英

Converting PHP BBCode REGEX to JavaScript, can someone help pinpoint an issue?

I am trying to convert the following PHP REGEX into JavaScript:

$article_f = preg_replace('#\[b\](.+)\[\/b\]#iUs', '<b>$1</b>', $article_text);

I have come up with the following JavaScript:

 article_f = article_f .replace(/\[b\](.+)\[\/b\]/gi, '<b>$1</b>');

For some reason this is allowing a match to go ignored if it is on the same line as another match, it will actually combine them into one large match, eg:

[b] this is bold[/b] and [b] this is too [/b]

Will be replaced with

<b> this is bold[/b] and [b] this is too </b>

Any ideas one how to fix this would be greatly appreciated.

use this pattern instead:

/\[b\](.+?)\[\/b\]/gi

the problem was that + quantifier was greedy (default behaviour) and thus .+ captures all that he can (ie : this is bold[/b] and [b] this is too ). If you add a question mark the quantifier becomes ungreedy (=lazy) and stop at the first closing bbcode tag.

In the php pattern you can see the U modifier at the end which switch all greedy quantifiers to lazy and all lazy quantifiers to greedy. It's the reason why .+ in the php pattern is lazy.(The default behaviour is inverted).

You can notice too the s modifier in the php pattern. s stands for single line . That means that the dot can match newlines too. But Javascript doesn't have an equivalent. To have the same with Javascript you must replace the dot by [\\s\\S] , otherwhise .+ will stop the match at the first newline.

The "perfect" translation of the php pattern is:

/\[b\]([\s\S]+?)\[\/b\]/gi

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