当计数结果返回时,preg_match 在 php 中不起作用

问题描述 投票:0回答:5

我有一个示例文本:

$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

php
5个回答
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_match
    preg_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 匹配才能结束,并更改括号以获得真正的匹配。

<?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]);

© www.soinside.com 2019 - 2024. All rights reserved.