I'd like to extract a substring within a string but seems like strpos()
doesn't fidn my substring. I have the following code:
<?php
function get_string($string, $start, $end)
{
$pos = 0;
echo $string,"<br>-------------------------<br>";
echo $start;
$pos = strpos($string, $start);
echo "<strong>".$pos."</strong>";
if ($pos === false)
{ // Zero is not exactly equal to false...
return $pos;
}
$pos += strlen($start);
$len = strpos($string, $end, $pos)-$pos;
$found = substr($string, $pos, $len);
return $found;
}
$str='<table class="views-table cols-4"><thead><tr><th class="views-field views-field-line-item-title">
Title </th>
<th class="views-field views-field-commerce-unit-price">
Unit price </th>
<th class="views-field views-field-quantity">
Quantity </th>
<th class="views-field views-field-commerce-total views-align-right">
Total </th>
</tr></thead><tbody><tr class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">
"Sweet Heart" Package (SPA02) </td>
<td class="views-field views-field-commerce-unit-price">
135.00 CAD </td>
<td class="views-field views-field-quantity">
1 </td>
<td class="views-field views-field-commerce-total views-align-right">
135.00 CAD </td>
</tr></tbody></table>';
$str=strtr($str,array("<"=>"<","&"=>"&"));
echo get_string($str,'class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">','</td>');
?>
and get this oupt in the browser:
<table class="views-table cols-4"><thead><tr><th class="views-field views-field-line-item-title"> Title </th> <th class="views-field views-field-commerce-unit-price"> Unit price </th> <th class="views-field views-field-quantity"> Quantity </th> <th class="views-field views-field-commerce-total views-align-right"> Total </th> </tr></thead><tbody><tr class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title"> "Sweet Heart" Package (SPA02) </td> <td class="views-field views-field-commerce-unit-price"> 135.00 CAD </td> <td class="views-field views-field-quantity"> 1 </td> <td class="views-field views-field-commerce-total views-align-right"> 135.00 CAD </td> </tr></tbody></table>
-------------------------
class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">
and I woudl expect to see $pos
returning a number that is printed in html
- why does strpos()
nor return the expectd position?
Thanks!
Incorrect Answer
You have < in your needle string. &lt; is only needed if you encode special html characters for output.
[Edited]
Correct Answer
I should have ran the code before posted the above. The real issue is two many spaces in the needle string
replace
echo get_string($str,'class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">','</td>');
with
echo get_string($str,'class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">','</td>');