为什么我找不到带有 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>');
?>

并在浏览器中获取此输出:

<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 return 打印在 html 中的数字 - 为什么 strpos() 和 return 都不是预期的位置?

谢谢!

答案不正确

您有<;在你的针线中。 &仅当您为输出编码特殊 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>');