Reputation: 2731
Here is my string, nicely friendly error in a single string.
The service code name can not be empty at line 1.
The service code name can not be empty at line 2.
The service code name can not be empty at line 3.
The service code name can not be empty at line 4.
The service code name can not be empty at line 5.
The service code name can not be empty at line 6.
The service code name can not be empty at line 7.
The service code name can not be empty at line 8.
The service code name can not be empty at line 36.
I can count the occurrences using this regex exspression: '/line \d{1,}./'
With following code.
$regexStr = '/line \d{1,}./';
$occurences = preg_match_all($regexStr, $str, $matches);
However I want to return the array with the delimiter. For example:
- The service code name can not be empty at line 1.
- The service code name can not be empty at line 2.
- The service code name can not be empty at line 5.
I tried using
$result = preg_split($regexStr, $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
Without any joy, this just returned the string without the delimiter.
Also, if you are a regex expert, could you tell me how to exclude the intro ,
if it is the start of the string - very helpful!
I think the way to do it is using the preg_match_all()
with the $output
configured on param 3 of the method. However, I think my regex
is wrong that it doesn't include the proceeding bit?
Many thanks in advance.
Upvotes: 1
Views: 29
Reputation: 785146
You can use preg_match_all
with this regex:
/\w.+?line \d+\./
This regex starts matching from a word character and matches till 1+ digits followed by a dot.
Code:
if (preg_match_all('/\w.+?line \d+\./', $str, $m))
print_r($m[0]);
Array
(
[0] => The service code name can not be empty at line 1.
[1] => The service code name can not be empty at line 2.
[2] => The service code name can not be empty at line 3.
[3] => The service code name can not be empty at line 4.
[4] => The service code name can not be empty at line 5.
[5] => The service code name can not be empty at line 6.
[6] => The service code name can not be empty at line 7.
[7] => The service code name can not be empty at line 8.
[8] => The service code name can not be empty at line 36.
)
Upvotes: 4