Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在字符串中搜索以查找带有preg match all和regex的单词_Php_Search_Preg Match All - Fatal编程技术网

Php 在字符串中搜索以查找带有preg match all和regex的单词

Php 在字符串中搜索以查找带有preg match all和regex的单词,php,search,preg-match-all,Php,Search,Preg Match All,我试图编写一个搜索函数来搜索字符串并找到单词 比如php+mysql Select * From Column Where ID Like %Word% 我试图用Preg match all和regex编写相同的代码 这是我的密码 $strings = ' ( monstername 205 "Devil Troop of Desire") ( monstername 206 " Devil Troop of Pain " ) ( monstername 207 "De

我试图编写一个搜索函数来搜索字符串并找到单词

比如php+mysql

Select * From Column Where ID Like %Word%
我试图用Preg match all和regex编写相同的代码

这是我的密码

$strings = '
( monstername 205 "Devil Troop of Desire")
( monstername 206 "  Devil Troop of Pain     "  )
( monstername 207       "Devil Troop of Greed")
( monstername 208   "       Devil Troop of Jealousy  ")
( monstername 207 "Mask Troop of Greed"  )';

preg_match_all('/monstername\s*(.*?)\s*\"\s*\\b(Jealousy)\b\s*\"\s*\)/i', $strings, $matches, PREG_SET_ORDER);
foreach ($matches as $match){list (, $MonsterNumber) = $match;
echo "$MonsterNumber";
}
输出应该是

208
但它不能正确显示输出

当我用嫉妒的魔鬼队伍取代嫉妒时,它就表现出来了

我只想对php+mysql做同样的想法

我想要%Word%


如果不提供完整字符串以查找monster的编号,则部分\s*\\bJea不允许在引号和单词开头之间使用除空格以外的其他字符。你可能想要任何字符,甚至没有?在它们之间,例如。*\\b和单词后面的相同问题。

您必须更好地定义您要搜索的内容:嫉妒前后可能有空格/非空格、非引号字符

preg_match_all('/\( monstername\s*(\d+)\s*"\s*([^"]*\bJealousy\b[^"]*)\s*"\s*\)/i',
$strings, $matches, PREG_SET_ORDER);
或在搜索脚本中使用

preg_match_all('/\( monstername\s*(\d+)\s*"\s*([^"]*(Jealousy)[^"]*)\s*"\s*\)/i',
$strings, $matches, PREG_SET_ORDER);
对于每个匹配的怪物,它将返回匹配行、怪物编号、怪物名称和匹配模式:

Array
(
    [0] => Array
        (
            [0] => ( monstername 208   "       Devil Troop of Jealousy  ")
            [1] => 208
            [2] => Devil Troop of Jealousy
            [3] => Jealousy
        )
)

如果您只希望怪物编号作为输出,则此正则表达式只匹配编号,而不匹配其周围的任何内容,因为有“向前看”和“向后看”:

/(?<=monstername\s)\d+(?=.*Jealousy.*)/i

但是有了这个,在monstername和数字之间只能有一个空格字符。

我的正则表达式技能现在还不错,因为我昨天在PHP中使用了正则表达式。然而,我的问题是试图理解您试图做什么,为什么输出是208?如果它像mysql一样,你会有匹配的行数,但是得到208就像使用MAX返回一个结果一样:/嗯,它工作得很好,但是只写像。*\\bJea\b.*这样的Jea并获得输出是可能的,因为我试过了,但没有成功,这是一个搜索脚本