Jump to content

Get substring by referencing other substrings around it


lfernando

Recommended Posts

Hello,

 

Does anyone know how to get a substrig by referencing other substrings around it?

 

Ie, my string is the following:

 

These are my favorite foods:
<ul>
   <li id="1"> Pizza </li>
   <li id="2"> Burgers </li>
   <li id="three"> Hot Dogs </li>
</ul>

I need to get the ID of each list item, i know they will always follow "<li id=".

I also need to get the text of each list item, i know they will always be before "</li>"

 

Thanks!

A very rough 'sledge-hammer' approach...

<?PHP
$string ='These are my favorite foods:
<ul>
<li id="1"> Pizza </li>
<li id="2"> Burgers </li>
<li id="three"> Hot Dogs </li>
</ul>';

echo $string;

$new_array = explode("<li id=", $string);
$junk = array_shift($new_array);
$string = implode("~",$new_array);
$string = str_replace('"', "", $string);
$string = str_replace('> ', "|", $string);
$new_array = explode("~", $string);
$i=0;
$w=count($new_array);
while($i<$w) {
$t_array = explode("|",$new_array[$i]);
echo "this is the id  <B>" . $t_array[0] . "</b> and this is the accompanying text <i>" . $t_array[1] . "</i><br>";
$i ++;
}

?>

example output...

http://nstoia.com/test/dog.php

another option:

 

<?php
$string ='These are my favorite foods:
<ul>
<li id="1"> Pizza </li>
<li id="2"> Burgers </li>
<li id="three"> Hot Dogs </li>
</ul>';

$pattern = "/<li id=\"(.*)\">(.*)<\/li>/";

$result = preg_match_all($pattern,$string,$matches);

for ($i=0;$i<count($matches);$i++) {
echo "id: {$matches[1][$i]} value: {$matches[2][$i]} <br />";
}

?>

in retrospect, i should have used single quotes on the outside of $pattern so to not have to escape double-quotes on the inside:

 

$string ='These are my favorite foods:
<ul>
<li id="1"> Pizza </li>
<li id="2"> Burgers </li>
<li id="three"> Hot Dogs </li>
</ul>';

$pattern = '/<li id="(.*)">(.*)<\/li>/';

$result = preg_match_all($pattern,$string,$matches);

for ($i=0;$i<count($matches);$i++) {
echo "id: {$matches[1][$i]} value: {$matches[2][$i]} <br />";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.