RegExp does not take the input value

4

I need to extract the value of a tag html

<input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">

I am using a Expressão Regular to return the value of input

   $pattern = '~<input type=hidden id=X-Tmx-session-id name=X-Tmx-session-id value=(.*?) \/>~';
   preg_match($pattern, $get, $xArray);
   var_dump($xArray);

But my expression returns only an empty array: array(0) { }

I need to get only value of input

  

2530317385

    
asked by anonymous 22.04.2015 / 05:37

2 answers

3

Your RegEx is different than your html-input, just compare:

 <input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
~<input type=hidden id=X-Tmx-session-id name=X-Tmx-session-id value=(.*?) \/>~

The quotes are missing, the position requested by RegEx is different.

If you're getting an html by curl , why not use the DOM to get the elements? For example:

$get = '<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input value="test1">
<input value="test2">
<input value="test3">
</body>
</html>';

$doc = new DOMDocument();
@$doc->loadHTML($get); //O @ previne mostrar erro de HTML

$allInputs = $doc->getElementsByTagName('input');
foreach ($allInputs as $input) {
    echo $input->getAttribute('value'), '<br>';
}

Or with XPath (you may need more advanced selectors):

<?php
$get = '<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <input value="2530317381" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317382" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317383" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317384" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
</body>
</html>';

$doc = new DOMDocument();
@$doc->loadHTML($get);

$xpath = new DOMXpath($doc);
$doc = NULL;

$allInputs = $xpath->query('*/input[@id=\'X-Tmx-session-id\']');

foreach ($allInputs as $input) {
    echo $input->getAttribute('value'), '<br>';
}

Example online: link

    
22.04.2015 / 05:51
0

I also recommend using the DOM library, however I prefer to use this .

Now if you'd like to try the attempt with ER , try:

Example

$id = 'X-Tmx-session-id';

$pattern = "~(?=<input.*id=['\"]*{$id}['\"]*.*)<input.*value=['\"]*([^'\"]*)['\"]*.*~";

$get = '<input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">';

preg_match($pattern, $get, $xArray);

echo "<pre/>";
var_dump($xArray[1]);
    
22.04.2015 / 14:34