1

I have a problem with converting chars from a text file to a key value array. It ignore the spaces.

My text is like this:

type="lorem" template="lorem_ipsum.phtml" key1="lorem Ipsum" key2="lorem Ipsum" key2="lorem Ipsum"

The problem appears near the separator in my preg_match code, I lose the seconds words in key1 or key´2 values!

preg_match_all("/([^,= ]+)=([^,= ]+)/", $line_Content, $r);
$myarray = array_combine($r[1], str_replace('" ','',$r[2]));

Help!

3
  • What is the possible syntax here? Is the format always alphanumeric followed by = followed by " followed by anything but " terminated by "? Or is this more complex HTML-attribute-like syntax? Commented May 7, 2015 at 14:52
  • Can you please post the whole code? Commented May 7, 2015 at 14:52
  • @deceze: There is no html in the text, but it contains spaces and the key names key1, key2... My text have always an alphanumeric key, followed by = "text values " Commented May 7, 2015 at 15:00

2 Answers 2

5

This regex should match your intended text much better:

(\w+)="([^"]*)"

A word followed by an equal sign followed by a double quote, then anything up until the next double quote.

preg_match_all('/(\w+)="([^"]*)"/', $line_Content, $r);
$myarray = array_combine($r[1], $r[2]);

Note that this will fail for double quotes inside the double quotes, at which point you'd need escape sequences, at which point regular expressions become quite cumbersome.

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

1 Comment

Check this: stackoverflow.com/a/2039820/171318 .. If you are using it, your regex would be stable. +1 since it is not said that these are indeed attributes of an XML node.
3

It looks like attributes of an XML/HTML node. Why not letting a DOMParser doing our work?

$string = 'type="lorem" template="lorem_ipsum.phtml" key1="lorem Ipsum" key2="lorem Ipsum"';
$xml = '<foo ' . $string . ' />';

$doc = new DOMDocument();
@$doc->loadXML($xml);

$element = $doc->getElementsByTagName('foo')->item(0);
foreach($element->attributes as $attr) {
    $result [$attr->name] = $attr->value;
}

var_dump($result);

This is useful if you explicitly want to validate that the string is well formed. However, if your input isn't XML/HTML that it is not useful.

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.