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);
Changes I've done:
\\s
- you don't need matches of whitespaces $search
(parentheses around) preg_quote
var_dump
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.