Extract a value from an unordered list

I have an unordered list like this

<ul>
<li>Some text</li>
<li>Something else here</li>
<li>#345</li>
</ul>

I need to only take away the number that is in the third list item and filter everything else out. It is possible that a number could be found within the first or second list items.

How can I do a loop that extracts my number from the third <li> item every time and places it into a variable?

Does it matter where the number is or does it matter to just extract numbers from the string provided?

If it matters where the number is, you use regexp to match all <li></li> elements (probably with preg_match_all(“#<ul>([(.*)[1]]</ul>#”, $str, $matches); -> note, I could be wrong here) and then you explode the matches you got by </li> delimiter.
Then you loop trough the array you just got and you use regexp to match the digits. If digit is matched, you’re done.
I could post the entire code for this, but I’m kinda in a rush to leave home so I’m sorry for not doing it :slight_smile:


  1. </ul> ↩︎

This should do it.


<?php
error_reporting(-1);
ini_set('display_errors', true);

$html = '
<ul>
  <li>Some text</li>
  <li>Something else here</li>
  <li>#345</li>
</ul>';

$dom = new DOMDocument;
$dom->loadHTML($html);

echo preg_replace(
  '~[^0-9]~',
  null,
  $dom->getElementsByTagName('li')->item(2)->nodeValue
);

/*
  345
*/

If you are sure that the numbers can happen only once in the string then you can easily extract with regex though I am not regex expert.


$string = '<ul>
<li>Some text</li>
<li>Something else here</li>
<li>#345</li>
</ul>';
preg_match_all('/([0-9]+)/S', $string, $matches);
echo '<pre>'; print_r($matches);die();

Otherwise the domdocument library as Anthony suggested already.

yeah the tricky bit here is that it is possible that numbers may exist in the first or second list items. So I can’t do a match for numbers on the whole list.

Thanks to AnthonySterling for this bit:

$dom->getElementsByTagName('li')->item(2)->nodeValue

that should help me look at only the third list item!