Try not to get too hung up on a specific function like preg_match()
. PHP offers several ways to generate your desired output. I'll show you three different approaches:
Input:
$response = "Response: 311768560
311768562
311768564";
Method #1: explode()
with substr()
and strpos()
(Demo)
$array = explode("\r\n", substr($response, strpos($response, ' ') + 1));
*note, this method assumes that the first string (Response
) is the only unwanted substring and that it is always first. Also, the \r
may not be necessary depending on your coding environment. This is probably the fastest of my list of methods because it doesn't use regex, but it does require 3 function calls and one incrementation -- not to mention it may be too literal for your actual use case.
Method #2: preg_match_all()
(Demo)
$array = preg_match_all('/\d+/', $response, $out) ? $out[0] : [];
This method is very direct, fast, and requires minimal code. If there are any drawbacks at all, they are that the preg_match_all()
returns a true|false result and generates an output variable in the form of a multidimensional array. To modify this output to suit your one-dimensional requirement, I place an inline condition at the end of the function which delivers the desired data to $array
.
Method #3: preg_split()
(Demo)
$array = preg_split('/\D+/', $response, 0, PREG_SPLIT_NO_EMPTY);
This function behaves just like explode()
except it wields the power of regex. The pattern identifies all non-digital substrings and uses them as "delimiters" and splits the string on each of them. For your input, the first delimiter is "Response: ", then the newline character(s) after: "311768560" and "311768562". The beauty of preg_split()
is that it directly provides the one-dimensional array that you are seeking.
Output:
No matter which of the above methods you try, you will receive the same correct output: $array = array('311768560', '311768562', '311768564');
If any of these methods fail your actual use case, then it is probably the product of your $response
string being too different from the sample data that you have posted here.