Skip to content
Advertisement

Get all values inside quotes in php string

I have the following string:

<data value="https://thisurl.com">One description</data>
<data value="https://thaturl.com">Another description</data>

I want to display only the text inside the double quotes, in this case the urls. I’m using the following code:

<?php
preg_match_all('/".*?"|'.*?'/', $input, $array);
foreach ($array[0] as $key => $value) {
    echo $value;
}

This code extracts the urls from the string but is adding single quotes and I need the plain url without single or double quotes:

‘https://thisurl.com’ ‘https://thatsurl.com’

Any ideas how to fix this?

Advertisement

Answer

Why reinvent the wheel?

Use PHP’s SimpleXML parser to do the job;

<?php

    $xml = simplexml_load_string('<xml>
        <data value="https://thisurl.com">One description</data>
        <data value="https://thaturl.com">Another description</data>
    </xml>');
    foreach($xml as $node) {
        $url = (String) $node->attributes();
        echo $url . PHP_EOL;
    }

Output:

https://thisurl.com
https://thaturl.com

Based on comment (same output);

<?php

    $data_1 = '<data value="https://thisurl.com">One description</data>';
    $data_2 = '<data value="https://thaturl.com">Another description</data>';

    $xml = simplexml_load_string('<xml>' . $data_1 . $data_2 . '</xml>');
    foreach($xml as $node) {
        $url = (String) $node->attributes();
        echo $url . PHP_EOL;
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement