正则表达式无法匹配字符串

时间:2013-12-20 06:37:42

标签: php regex

我无法使用以下代码来匹配以下字符串,我不知道发生了什么

$regex = "/\\251/i";
if (preg_match($regex, $contents)) {
  echo 'good it works';
}

$内容如下

Shanghai Taipei Tokyo TorontoOxford is a registered trade mark of Oxford University Pressin the UK and in certain other countriesPublished in the United Statesby Oxford University Press Inc., New YorkRevised text \251 John Guy 2000

我已经尝试将字符串编码为没有运气

$contents = utf8_encode ($contents);

这适用于我使用的所有在线工具,我错过任何东西,看看为什么它在运行时不起作用?

3 个答案:

答案 0 :(得分:0)

在这种情况下,想要使用原始(非转义)反斜杠来匹配字符251(字符八进制0251是ISO-LATIN-1 copyright symbol)。

尝试简单地\251直接匹配©字符,因为您的内容看起来已经是UTF8编码了。

查看示例:http://regex101.com/r/eT3mZ8

答案 1 :(得分:0)

你应该尝试:

preg_match('/(\xA9)/i', $text);

或者:

preg_match('/(\251)/i', $text);

答案 2 :(得分:0)

我在PERL中尝试检查正则表达式是否正确。请找到以下perl代码,它具有完全匹配\ 251

的正则表达式
#!C:\Perl64\bin
$regex = "Shanghai Taipei Tokyo TorontoOxford is a registered trade mark of Oxford University Pressin the UK and in certain other countriesPublished in the United Statesby Oxford University Press Inc., New YorkRevised text \251 John Guy 2000";
if ("$regex" =~ m/(\251)/)
{
    print "Success scenario\n";
    print "$regex is matched \n";
} else {
    print "$regex is not matched \n";
}

这将输出 - >

Success scenario
Shanghai Taipei Tokyo TorontoOxford is a registered trade mark of Oxford Univers

ity Pressin英国和其他一些国家在美国出版 y牛津大学出版社,纽约修订文本\ 251 John Guy 2000匹配

希望这可以帮到你

由于