0

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("/^\n*\s*(Hello|World!)\s*$/i",$x,$m))

 {print_r($m);}

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

3
  • Your code shouldn't be matching anything. Are you sure that it matches the second line? Commented Dec 11, 2015 at 6:39
  • print_r($m); returns Array([0]=>[1]=World!) Commented Dec 11, 2015 at 6:43
  • 1
    This shouldn't be happening if x indeed is a single string with two words separated by a newline. The alternation allows for only one of the words to match, and the anchors that tie the match to the start and end of the string are outside of the alternation, which means both must match for the regex to succeed - and that means that the string can only match if there is exactly one word in it . If you had used the /m modifier, they would also have matched at the start/end of each new line, but that modifier isn't being used... Commented Dec 11, 2015 at 6:55

3 Answers 3

1
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 \n*\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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

 $x="Hello    
 world! ";

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

echo count($m)

Output

2

Phpfiddle Preview

Comments

1

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.

/^(.+?)[\n,\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("/^(.+?)[\n,\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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.