PHP正则匹配字符串中的标签

如果标签里面有中文、英文、数字等混排,则需要对汉字进行特殊处理,由于PCRE不支持\U \P \L之类的perl字符串处理转义,使用16进制或者Unicode进行处理,范例如下:

[coolcode lang=”php”]

$str = “之二宽阔的甘家口东#标签1#标签2 #标签3。#标签4,都发$1234 ¥xc,cvm , ¥12,dflksjf如何#标签5.x #tag6.cvxcv“”;
preg_match_all(‘/#([a-zA-Z0-9\x7f-\xff]+)/’, $str, $mat);
print_r($mat);

preg_match(“/[\x{00a5}\x{ffe5}](\d+)/u”, $str, $mat);
print_r($mat);

[/coolcode]

得到的结果如下:


Array
(
[0] => Array
(
[0] => #标签1
[1] => #标签2
[2] => #标签3。
[3] => #标签4
[4] => #标签5
[5] => #tag6
)

[1] => Array
(
[0] => 标签1
[1] => 标签2
[2] => 标签3。
[3] => 标签4
[4] => 标签5
[5] => tag6
)

)
Array
(
[0] => ¥12
[1] => 12
)

补充说明:

双字节字符编码范围

1. GBK (GB2312/GB18030)
x00-xff GBK双字节编码范围
x20-x7f ASCII
xa1-xff 中文 gb2312
x80-xff 中文 gbk

2. UTF-8 (Unicode)

u4e00-u9fa5 (中文)
x3130-x318F (韩文
xAC00-xD7A3 (韩文)
u0800-u4e00 (日文)

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image