regex pattern to find this particular string in file_get_contents in PHP

914 views Asked by At

I'm looking to get this value 'B00DS4KJR4' enclosed in tags from a url by using file_get_contents() function in PHP. However, I'm failing to write the correct regex to find the value from this html source code the page:

<span class="a-text-bold">ASIN:
                    </span>
                    <span>B00DS4KJR4</span>

Can you help me to write the correct regex to find that particular value on the page ?

2

There are 2 answers

0
Grokify On BEST ANSWER

You can use a regular expression like the following also presented on Regex101. This looks for a <span> with any attributes, containing the string ASIN: in the innerHTML followed by another <span> and captures the contents of the second <span>.

$html ='<span class="a-text-bold">ASIN:
                </span>
                <span>B00DS4KJR4</span>';

if (preg_match('/<span\s[^><]*>\s*ASIN:\s*<\/span>\s*<span>\s*([^><]*)\s*<\/span>/i', $html, $m)) {
    $asin = $m[1];
    print $asin;
}
1
b14r On
preg_match_all('/<span>(.*)<\/span>/',$the_html,$the_result_array);

The first span doesn't match with the regex because it has class in it, the other ones which are written like <span>anything</span> will be found.