简体   繁体   中英

preg_match not working in php when count result return

I have a sample text:

$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);

When i echo count($match_words) is result return is null

How to fix it output is 2

这样的事情可能会做到:

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

First, when you do this, always use preg_quote around $search to escape your regex delimiter.

Then, your code is perfectly fine (even without preg_quote ). It outputs 3 for me. You may have file encoding issue due to non-ASCII characters in your string. Have you tried using UTF8?

Change it to:

$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

Changes I've done:

  1. Removed parentheses around \\s - you don't need matches of whitespaces
  2. Added matching group for $search (parentheses around)
  3. Added preg_quote
  4. Introduced var_dump
  5. Changed preg_match to preg_match_all

PS: probably \\b instead of \\s would be better to use

Use:

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

instead of your preg_match

You have to use preg_match_all with /u modified for unicode matching to end, And change the paranthesis to get the real matches.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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