我想在字符串中提取一个子字符串,但似乎strpos()
不会填充我的子字符串。我有以下代码:
<?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>');
?>
并在浏览器中获取此信息:
<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">
我希望看到$pos
返回html
中打印的数字 - 为什么strpos()
也不会返回预期的位置?
谢谢!
答案 0 :(得分:2)
答案错误
你有&amp; lt;在你的针线。 &安培; LT;仅在为输出编码特殊html字符时才需要。
[被修改]
正确答案
我应该在发布上面之前运行代码。真正的问题是针串中有两个空格
替换
echo get_string($str,'class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">','</td>');
与
echo get_string($str,'class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">','</td>');