如何在php正则表达式中逐行匹配字符串?

I have string with multiple newlines, each new line contains a new substring.

Here is an example of the string with 2 lines :

 $x="Hello
       World!

You can see Hello is in the first line and World! is in a newline.

Each substrings start and end with or without a newline(s)|space(s).

I want to match both lines.

My currunt code matched the second line and ignored the first.

 if(preg_match_all("/^
*\s*(Hello|World!)\s*$/i",$x,$m))

 {print_r($m);}

Is there any way to fix this,so that both lines can be matched?

if(preg_match_all("/(Hello|World!)/i",$x,$m))
{
 print_r($m);
}

If you user ^ $ it matches only the full line. So the Hello part has no *\s* before Hello so it won't match. If you change the script like above, it will only lookup for the words, reagless of having any stuff before or after the word.

Hope that helps.

Try this

 $x="Hello    
 world! ";

preg_match_all("#\b(Hello|World!)\b#",$x,$m) ;

echo count($m)

Output

2

Phpfiddle Preview

I'm not sure what the "goal" is but this regex will match both lines. I changed your Hello|World to (.+?) as it matches any character and so would match variables if you are parsing code.

/^(.+?)[
,\s,\t]{1,8}(.+?)$/

Here is your example with the new regex, so if I misinterpreted you can see what's going on.

<?php 

 $x="Hello
      World!";

 if(preg_match_all("/^(.+?)[
,\s,\t]{1,8}(.+?)$/i",$x,$m))

 {print_r($m);}

?>

you'll need to determine what and how many potential characters are between the first and second lines if your parsing more than a single series, and then modify the {1,8} to suit spaces, tabs, newlines, etc...