0

I'm using the following code to split a string into an array of matches:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);
print_r($matches);

The result is:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name=
            [3] => "first_name"
            [4] => label=
            [5] => "First Name"
        )

)

But I need the result to be:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name="first_name"
            [3] => label="First Name"
        )

)

I tried this but it didn't work:

preg_match_all('/="(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);

Can anyone tell me where I'm going wrong? Thanks

6
  • 2
    explode(' ',$string); Commented Jan 25, 2019 at 8:12
  • Are you trying to use RegEx for HTML string? Commented Jan 25, 2019 at 8:12
  • The main issue I see is that | which implies to search for either any text that is between quotation marks or any text that is not a space or double quote. You would be better served either by an explode to simply split text values or if you really need regex for whatever reason something that is similar to: ([^\s"]+(="\w*")*). I'm a bit exhausted so it may not be exactly that but more or less should give you a jumping point. Commented Jan 25, 2019 at 8:19
  • @splash58: That was my first thought as well, but no it won't work because it will split label="First Name" into separate values since it has a space in Commented Jan 25, 2019 at 8:19
  • @Justinas No, the string in my question is not HTML Commented Jan 25, 2019 at 8:20

2 Answers 2

2

You can use pattern /\s(?![\w\s]+\")/ in preg_split() to split string by space that isn't in value.

$res = preg_split("/\s(?![\w\s]+\")/", $text);

Check result in demo

Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work if there is more than one space in the value 3v4l.org/T9CWh
@Mohammad Thanks for your help, but actually Nick is correct and this problem is not solved, it needs to work with any number of spaces
@TheBobster I can't understand problem, it work also for multiple space 3v4l.org/ag1He
@Mohammad Ok it looks like you edited the answer and now it works with multiple spaces, so thank you!
What's about name="first diff-name" ?
0

If you want to use preg_match_all here's a working code:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('([a-zA-Z_]*[=]["][a-zA-Z_]*["]|[a-zA-Z_]*[=]["][ a-zA-Z]*["]|[a-zA-Z]+)', $text, $matches);
print_r($matches);

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.