简体   繁体   English

PHP正则表达式替换不匹配

[英]PHP regex replacement doesn't match

I'm using this regex to get house number of a street adress. 我正在使用此正则表达式获取街道地址的门牌号码。

[a-zA-ZßäöüÄÖÜ .]*(?=[0-9])

Usually, the street is something like "Ohmstraße 2a" or something. 通常,这条街是“Ohmstraße2a”之类的东西。 At regexpal.com my pattern matches, but I guess preg_replace() isn't identical with it's regex engine. 在regexpal.com上,我的模式匹配,但是我猜preg_replace()与它的regex引擎不相同。

$num = preg_replace("/[a-zA-ZßäöüÄÖÜ .]*(?=[0-9])/", "", $num);

Update: It seems that my pattern matches, but I've got some encoding problems with the special chars like äöü 更新:似乎我的模式匹配,但是我遇到了一些特殊字符的编码问题,例如äöü

Update #2: Turns out to be a encoding problem with mysqli. 更新#2:原来是mysqli的编码问题。

First of all if you want to get the house number then you should not replace it. 首先,如果您想获得门牌号,那么您不应该替换它。 So instead of preg_replace use preg_match . 因此,使用preg_match代替preg_replace

I modified your regex a little bit to match better: 我对您的正则表达式进行了一些修改以使其更好地匹配:

$street = 'Öhmsträße 2a';

if(preg_match('/\s+(\d+[a-z]?)$/i', trim($street), $matches) !== 0) {
    var_dump($matches);
} else {
    echo 'no house number';
}
  1. \\s+ matches one or more space chars (blanks, tabs, etc.) \\s+匹配一个或多个空格字符(空格,制表符等)
  2. ( ... ) defines a capture group which can be accesses in $matches ( ... )定义了一个捕获组,可以在$matches进行访问
  3. \\d+ matches one or more digits (2, 23, 235, ...) \\d+匹配一个或多个数字(2、23、235等)
  4. [az] matches one character from a to z [az]从a到z匹配一个字符
  5. ? means it's optional (not every house number has a letter in it) 表示它是可选的(并非每个门牌号都有一个字母)
  6. $ means end of string, so it makes sure the house number is at the end of the string $表示字符串的结尾,因此要确保门牌号在字符串的结尾

Make sure you strip any spaces after the end of the house number with trim() . 确保在门牌号结尾之后使用trim()去除所有空格。

u修饰符有时可以帮助处理“多余”字符。

I feel this may be a character set or UTF-8 issue. 我觉得这可能是字符集或UTF-8问题。

It would be a good idea to find out what version of PHP you're running too. 找出您也正在运行的PHP版本是一个好主意。 If I recall correctly, full Unicode support came in around 5.1.x 如果我没记错的话,完整的Unicode支持出现在5.1.x左右。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM