Php 替换数组中的字符串

Php 替换数组中的字符串,php,str-replace,Php,Str Replace,我有一个长字符串,其中包含一个样式化的标记,我想删除它并用其他字符串替换它。 但是我尝试了str_replace函数,但是失败了。你知道我怎么做吗?我的密码在这里 $primaryNav = '<li id="menu-item-1178" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1178 sf-ul"> <a href="http://m

我有一个长字符串,其中包含一个样式化的标记,我想删除它并用其他字符串替换它。 但是我尝试了str_replace函数,但是失败了。你知道我怎么做吗?我的密码在这里

$primaryNav = '<li id="menu-item-1178" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1178 sf-ul">
                <a href="http://mysite.com/join/" class="sf-with-ul">
                    <cufon class="cufon cufon-canvas" alt="Get " style="width: 30px; height: 15px; ">
                        <canvas width="45" height="16" style="width: 45px; height: 16px; top: -1px; left: -2px; "></canvas>
                        <cufontext>Get </cufontext>
                    </cufon>
                    <cufon class="cufon cufon-canvas" alt="in" style="width: 15px; height: 15px; ">
                        <canvas width="24" height="16" style="width: 24px; height: 16px; top: -1px; left: -2px; "></canvas>
                        <cufontext>in</cufontext>
                    </cufon>
                    <span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span></a>
                        <ul class="sub-menu" style="visibility: hidden; display: none; "> </ul>
                </li>';

$primaryNav = str_replace('<span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span>', ' It works!', $primaryNav);
$primaryNav=”
    • '; $primaryNav=str_replace(“»”,“它有效!”,$primaryNav);
      您需要考虑标记之间的空格。在这种情况下,正则表达式可能是一个不错的解决方案:

      $primaryNav = preg_replace('#<span class="sf-sub-indicator">\s*<cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; ">\s*<canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; ">\s*</canvas>\s*<cufontext>»</cufontext>\s*</cufon>\s*</span>#', 'It works!', $primaryNav);
      

      请注意,最后一个将在第一个
      时停止匹配,因此如果有多个,则需要小心-正则表达式不支持这种“平衡”。

      “我想删除并替换为其他内容。”这是什么?你想替换什么。请说得更具体一些,再加上一些描述。@Lion我想用其他字符串替换。你在试哪一个?我已经测试了这两种方法,它们都有效。你能试试第二个吗?
      $primaryNav = preg_replace('#<span class="sf-sub-indicator">.*?</span>#', 'It works!', $primaryNav);