如何匹配 php 中的字符串模式


How to match the string patterns in php

我有一个字符串数组

$x=array("Hello","How","You","iam","fine") 

我试图提取一个带有这样的模式的字符串

$y=preg_grep ("/Hello('w+)/", $x);
print_r($y);

我想进行多个模式搜索并仅使用一个preg_grep返回,任何人都可以帮助我。

则表达式量词+表示match 1 or more times。字符串 Hello 不适合,因为 Hello 后有 0 个符号。使用*量词,表示match zero or more times

$x=array("Hello","How","You","iam","fine");
$y=preg_grep ("/Hello('w*)/", $x);
print_r($y);
// outputs: Array ( [0] => Hello )

你可以尝试这样的东西:

$y = preg_grep("/(PATTERN_1|PATTERN_2)/", $x);

请问您为什么不想在您的模式上使用循环?

你可以

试试这个,

<?php    
    $x=array("Hello","How","You","iam","fine");
    $y=preg_grep ("/H('w*)|Y('w*)/", $x);
    print_r($y);
?>