RhymeGuy
RhymeGuy

Reputation: 2122

PHP - how to extract this value from html?

HTML:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="12345678" />
<input type="hidden" name="_wp_http_referer" value="someurl/?album=1&amp;gallery=15" />

I need to get id of gallery which in this case is 15.

How im trying to accomplish this:

$html = <input type="hidden" id="_wpnonce" name="_wpnonce" value="12345678" />
<input type="hidden" name="_wp_http_referer" value="someurl/?album=1&amp;gallery=15" />";
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXpath( $dom);
$galleryid = $xpath->query(//how to get gallery id?); 

Upvotes: 0

Views: 846

Answers (5)

Sivasailanathan
Sivasailanathan

Reputation: 135

You can use the parse_url function in order to get the query string value. Check the parse_url function manual.

For example:

$url = 'http://example.com/path?arg=value#anchor';   
print_r(parse_url($url));

Upvotes: 1

Jens Erat
Jens Erat

Reputation: 38732

This is simple enough string manipulation which can be performed using XPath 1.0.

substring-after(//input/@value, 'gallery=')

Yet using parse_url like proposed in another answer is probably the more elegant solution, but this depends on your use case. Using XPath string manipulation could be reasonable for example if you need to use this as intermediate result for filtering in a predicate.

Upvotes: 0

user523736
user523736

Reputation: 549

If you need a simple solution:

$found = preg_match('/gallery=[0-9]+/', $html, $match);
$gallery_id = (int)substr($match[0], strlen("gallery="));

Upvotes: 0

RhymeGuy
RhymeGuy

Reputation: 2122

$html = <input type="hidden" id="_wpnonce" name="_wpnonce" value="12345678" />
<input type="hidden" name="_wp_http_referer" value="someurl/?album=1&amp;gallery=15" />";
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXpath( $dom);
$galleryid = $xpath->query('//input')->item(1); //get second input
parse_str($galleryid);
echo $gallery;

Upvotes: 0

Jamie Redman
Jamie Redman

Reputation: 431

Updating my answer as more detail was provided.

The xQuery path you want to use is (this is based on the html you provided, ie the input nodes are at the root of the document)

/input[@name='_wp_http_referer']/@value

This will allow you to extract the value from the input field. After you have done that you can use a regular expression to extract, so building on your sample above

$html = <input type="hidden" id="_wpnonce" name="_wpnonce" value="12345678" />
<input type="hidden" name="_wp_http_referer" value="someurl/?album=1&amp;gallery=15" />";
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXpath( $dom);
$referer = $xpath->evaluate("/input[@name='_wp_http_referer']/@value"); 

if(!empty($referer))
{
    $doesMatch= preg_match("/gallery\=(\d+)/", $referer, $matches);
    if($doesMatch > 0)
    {
        $gallery=$matches[1];
    }
}

Upvotes: 0

Related Questions