为什么我找不到带有 strpos() 的子字符串


why can i not find a substring with 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>');
?>

并在浏览器中获取此 oupt:

<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()也不返回预期的位置?

谢谢!

错误答案

您的针串中有 <。仅当您对用于输出的特殊 html 字符进行编码时才需要 &amplt;。

[已编辑]

正确答案

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

取代

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>');