1

I'm trying to create a simple PHP script that retrieves info from a string and puts it into an array. Ive looked around on some sites on multi capture regex for one pattern but can't seem to get the output im looking for

Currently this is my script.

$input = "username: jack number: 20";
//$input = file_get_contents("test.txt");

preg_match_all("/username: ([^\s]+)|number: ([^\s]+)/", $input, $data);

var_dump($data);

Which produces this output:

0 => 
    array (size=2)
      0 => string 'username: jack' (length=14)
      1 => string 'number: 20' (length=10)
  1 => 
    array (size=2)
      0 => string 'jack' (length=4)
      1 => string '' (length=0)
  2 => 
    array (size=2)
      0 => string '' (length=0)
      1 => string '20' (length=2)

Im looking to get the data into the form of:

0 =>
  array (size=x)
    0 => string 'jack'
1 =>
  array (size=x)
    0 => string '20'

Or two different arrays where the keys correspond to the same user/number combo

2 Answers 2

2

You can use match-reset \K:

preg_match_all('/\b(?:username|number):\h*\K\S+/', $input, $data);

print_r($data[0]);
Array
(
    [0] => jack
    [1] => 20
)

RegEx Breakup:

\b                    => a word boundary
(?:username|number)   => matches username or number. (?:..) is non-capturing group
:\h*                  => matches a colon followed optional horizontal spaces
\K                    => match reset, causes regex engine to forget matched data
\S+                   => match 1 or more non-space chars

Or else you can use a capturing group to get your matched data like this:

preg_match_all('/\b(?:username|number):\h*(\S+)/', $input, $data);

print_r($data[1]);
Array
(
    [0] => jack
    [1] => 20
)
Sign up to request clarification or add additional context in comments.

2 Comments

that would be great if you describe for OP what RegEx is doing, I mean by splitting it like / starting of expression
Yes added it in the answer now.
0
(?<=username:|number:)\s*(\S+)

You can use lookbehind here.See demo.

https://regex101.com/r/mG8kZ9/10

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.