Home > Back-end >  preg_match_all returns only last matches from single row , but all matches from multi row string
preg_match_all returns only last matches from single row , but all matches from multi row string

Time:05-27

I try to find all occurrences of sub-string in text, using preg_match_all function:

<?php

$str = '<p>this <a href="https://api.slack.com/apps/" target="_blank">link</a> and <a href="https://www.google.com" target="_blank">link 2</a></p>';



$reg = '/<a.*href="([^"] )"[^>] >(. )<\/a>/';

preg_match_all($reg, $str, $m);

print_r($m);

but above code returns only last link: run php online

When I split source text into rows, same code return all matches:

<?php

$str = '<p>this <a href="https://api.slack.com/apps/" target="_blank">link</a> and 
the <a href="https://www.google.com" target="_blank">link 2</a></p>';



$reg = '/<a.*href="([^"] )"[^>] >(. )<\/a>/';

preg_match_all($reg, $str, $m);

print_r($m);

php sandbox here

CodePudding user response:

The problem is your regular expression, you can limit the charecters:

/<a\s*href="([^"] )"[^>] >([^<] )<\/a>/

Or use lazy matching:

/<a.*?href="([^"] )"[^>] >(. ?)<\/a>/
  • Related