开发者

Php Regex: How to make a submatch optional if is at the end of subject

$text = 'something here *ls67 another thing'; // match
$text2 = 'something here *ls67. another th开发者_开发知识库ing'; // match
$text3 = 'something here  another thing *ls67.'; // match
$text3 = 'something here  another thing *ls67'; // doesn't match (and i need to match this)

$pattern = '|^(.*)?(\*[0-9a-zA-Z_-]{3,15})([^0-9a-zA-Z_-])+(.*)?$|i';

I've tried this pattern but it generates an error:

$pattern = '|^(.*)?(\*[0-9a-zA-Z_-]{3,15})([^0-9a-zA-Z_-]|$)+(.*)?$|i'; // Unknown modifier '$'
// and
$pattern = '|^(.*)?(\*[0-9a-zA-Z_-]{3,15})(([^0-9a-zA-Z_-])+|$)(.*)?$|i'; // same error


Since you're using | as your delimiter, you need to escape any |'s that appear in the pattern (or you could change it to a character that doesn't appear in your pattern, such as #. Since you introduced unescaped |'s in your second block of code, PCRE tries to take the characters following (staring with $) as modifiers, hence the error.

This should work:

$pattern = '#^(.*)?(\*[0-9a-zA-Z_-]{3,15})([^0-9a-zA-Z_-]+(.*)?|$)#i';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜