2012-02-29 60 views
2

我有以下的正则表达式:PHP的preg_replace问题

$patterns = array 
(
    '/\b(gubalowka hegy)\b/i', 
    '/\b(krakkó|wawel|wawelban|auschwitz|auschwitzba|auschwitz-birkenua)\b/i', 
    '/\b(királyi|város|fogaskerekű|séta)\b/i', 
); 

$replaces = array 
(
    '<strong>$1</strong>', 
    '<u><em>$1</em></u>', 
    '<strong>$1</strong>', 
); 

preg_replace($patterns, $replaces, $text); 

的问题是,只有一些单词被替换。

通过这个例子只是这些话:

Séta    => <strong>Séta</strong> 
Krakkó    => <u><em>Krakkó</em></u> 
királyi   => <strong>királyi</strong> 
Auschwitz-Birkenua => <u><em>Auschwitz-Birkenua</em></u> 

该换句话说留不变。

我试图让它工作的几种方法(单独替换每个单词,取代没有数组的单词),但他们都没有工作。

在这里,你可以检查一下: http://adriaholiday.dev.webndev.hu/ajanlatok/lengyelorszagi-hetvege.html

正则表达式得到记录在Chrome浏览器开发控制台

有人能帮忙吗?谢谢。

编辑:

如果我写的正则表达式,它的工作原理

$pattern = '/\b(krakkó|wawel|wawelban|auschwitz|auschwitzba)\b/iu' 
$replace = '<strong><u>$1</u></strong>'; 
$text = preg_replace($pattern, $replace, $text); 

问题只出现在正则表达式获取生成

$replace = '<strong>$1</strong>'; 

foreach (...) 
{ 
    $words .= "|{$word}"; // first vertical bar removed ... 
} 

// encoding UTF8 
// pattern: /\b(krakkó|wawel|wawelban|auschwitz|auschwitzba)\b/iu 
$pattern = '/\b(' . $words . ')\b/iu'; 

$text = preg_replace($pattern, $replace, $text); 
+0

这可能是一个与ASCII与Uni​​code的问题 - 我很长时间没有用PHP正则表达式做很多事情,但这可能是一个区域。 php如何处理不区分大小写的unicode字符串? – 2012-02-29 09:54:23

+0

将'u'加到你的修饰符('/ foo/iu')来告诉PCRE把这个模式当做UTF-8。看到http://php.net/manual/en/reference.pcre.pattern.modifiers.php – rodneyrehm 2012-02-29 10:03:36

+0

我已经尝试过“你”,它并没有帮助连接后 – csanyigabor 2012-02-29 10:08:51

回答

1

检查MBSTRING和mbregex可用。 PHP的默认类型,ISO-8859-1不包括ő,ű,Ő和Ű以及其他特殊字符(但我假设您只需要这些)。 UTF-8确实如此,但您必须使用多字节功能。

要阅读有关mbstring的更多信息,请参阅PHP documentation。它也包括mb_ereg_replace。

编辑:我发现用u标志,preg_repace也可以使用UTF-8。看看this question

+0

我试过用u标志,但它没有'改变任何东西,我现在尝试与mb_ereg_replace – csanyigabor 2012-02-29 10:09:41