1

Suppose I have the following in a text file:

xxa name="round_xx
Number 1
xxcolspanxx
DOG

yya name="round_yy
Number 2
xxcolspanxx
DOG

zza name="round_zz
Number 3
xxcolspanxx
DOG

I want to use PHP's preg_match_all() function to return all sequences within the text file that start with:

a name="round_

.. has any sequence of characters and newlines in between, and then ends with:

colspan

So the result should be these 3 matches:

a name="round_xx
Number 1
xxcolspan
a name="round_yy
Number 2
xxcolspan
a name="round_zz
Number 3
xxcolspan

This is my code, which fails. It reads the contents of the text file in to $page_contents, but the preg_match_all is producing totally incorrect matches:

$page_contents = file_get_contents('./path/to/textfile.txt');
$matches1 = array();
preg_match_all('/a name="round_(.*)colspan/s', $page_contents, $matches1);

I'm using PHP 7.1.28, Windows 10. Thanks.

Toto
  • 83,193
  • 59
  • 77
  • 109
Callum
  • 425
  • 1
  • 3
  • 14

1 Answers1

3

Make the regex non greedy:

preg_match_all('/a name="round_(.*?)colspan/s', $page_contents, $matches1);
//                              __^
Toto
  • 83,193
  • 59
  • 77
  • 109