2012-05-18 97 views
0

我有一个示例文本:的preg_match在PHP不工作时,计数结果返回

$text = "ác, def ác ghi ác xyz ác, jkl"; 
$search = "ác"; 
$_x_word = '/(\s)'.$search.'(\s)/i'; 
preg_match($_x_word, $text, $match_words); 
echo count($match_words); 

当我回声计数($ match_words来)的结果恢复为空

如何修复它输出为2

+0

http://ideone.com/KbkII ---你确定你试过运行它吗? – zerkms

+0

ps:使用'var_dump($ match_words);' – zerkms

+0

@zerkms:var_dump($ match_words)=>空 –

回答

0

像这样的东西可能会做到这一点:

echo \preg_match_all('/\sác\s/i', "ác, def ác ghi ác xyz ác, jkl");

+1

你有什么改变? – zerkms

+0

在这个例子中,括号中的'\ s'做什么? – alex

0

首先,当您这样做时,请始终使用preg_quote$search来逃避您的正则表达式分隔符。

然后,你的代码是完全正常的(即使没有preg_quote)。它为我输出3。由于字符串中包含非ASCII字符,您可能会遇到文件编码问题。你有没有尝试过使用UTF8?

0

将其更改为:

$text = "ghi ác xyz ác, jkl"; 
$search = "ác"; 
$_x_word = '/\s(' . preg_quote($search) . ')\s/i'; 
preg_match_all($_x_word, $text, $match_words); 
var_dump($match_words); 

http://ideone.com/hZD3X

变化我做:

  1. 删除的括号\s - 你不需要空格
  2. 添加匹配的匹配组为$search(圆括号)
  3. 新增preg_quote
  4. 介绍var_dump
  5. 改变preg_matchpreg_match_all

PS:可能的\b代替\s会更好地使用

0

用途:

preg_match_all($_x_word, $text, $match_words, PREG_SET_ORDER); 

,而不是你的preg_match

0

您必须使用preg_match_all并将/u修改为unicode匹配才能结束,并更改paranthesis以获得真正的匹配。

<?php 
    $text = "ác, def ác ghi ác xyz ác, jkl"; 
    $search = "ác"; 
    $_x_word = '/\s('.$search.')\s/ui'; 
    preg_match_all($_x_word, $text, $match_words); 

    //full matches (with spaces) 
    var_dump($match_words[0]); 
    //only ác matches. 
    var_dump($match_words[1]);