为什么我找不到strpos()的子串?

时间:2015-01-19 02:24:47

标签: php strpos

我想在字符串中提取一个子字符串,但似乎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("<"=>"&lt;","&"=>"&amp;"));
 echo get_string($str,'class="odd views-row-first views-row-last">&lt;td    class="views-field views-field-line-item-title">','&lt;/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()也不会返回预期的位置?

谢谢!

1 个答案:

答案 0 :(得分:2)

答案错误

你有&amp; lt;在你的针线。 &安培; LT;仅在为输出编码特殊html字符时才需要。

[被修改]

正确答案

我应该在发布上面之前运行代码。真正的问题是针串中有两个空格

替换

echo get_string($str,'class="odd views-row-first views-row-last">&lt;td    class="views-field views-field-line-item-title">','&lt;/td>');

echo get_string($str,'class="odd views-row-first views-row-last">&lt;td class="views-field views-field-line-item-title">','&lt;/td>');