-2

I have a bunch of H4 tags like this:

<h4 class="heading--35F23 headingh4--2x5Gb" data-reactid="26">MobilePay</h4>

How do I extract the value "MobilePay"?

Best Crox.

Scrox
  • 1
  • 2

1 Answers1

0

if you are talking about parsing data from a string, the easiest way to do so is to use a regular expression. In case if you already have your string:

$your_data = '<h4 class="heading--35F23 headingh4--2x5Gb" data-reactid="26">MobilePay</h4>';

preg_match_all('/<h4.*>(.*)<\/h4>/U', $your_data, $matches);
$result = $matches[1];

print_r($result);
Max Shaian
  • 418
  • 4
  • 11
  • **Don't** [parse HTML with a regex!](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – 0stone0 May 13 '20 at 12:22
  • A completely agree with the statement, but in the current case it's the easiest and fastest way to do that. There is no need to structure an elaborate html code, it's just a way to find certain values in a predefined pattern basically. Especially, if the string has already been requested. – Max Shaian May 13 '20 at 12:25
  • "a bunch of H4 tags" You have no idea how many, or how they look. A newline char for example will return unwanted results. Why not use default PHP functions like DOMDocument – 0stone0 May 13 '20 at 12:31
  • @0stone0. Exactly, it's a better practice, that's why I wrote - the easiest way. New lines after h4 won't spoil the results. An example of h4 has been provided. In case if we want to make a decent parser, we need to use DOM, trim the result and many other conditions. Also to write a class, unit tests etc. I just wanted to help the user right away, as it may be a one-time task. Anyway, thanks for pointing it out for other users. – Max Shaian May 13 '20 at 12:35
  • Thanks all, i have now done this: for ($i = 0; $i <= sizeof($h4); $i++) { preg_match_all('/(.*)<\/h4>/U', $h4[$i], $matches); $result = $matches[1][0]; $output .= $result; $output .= ","; } but i am getting this output: PHP Notice: Undefined offset: 24 in /home/crox/Kron Web Scraper/scrape.php on line 27 PHP Notice: Undefined offset: 0 in /home/crox/Kron Web Scraper/scrape.php on line 28 PHP Notice: Undefined variable: subs in /home/crox/Kron Web Scraper/scrape.php on line 48 – Scrox May 13 '20 at 12:41