douban2014 2012-08-23 13:45
浏览 33
已采纳

如何在不使用HTML标记的情况下查找字符串中的最后一个空格(正则表达式PHP)

I'm searching for a regex to find the last occurence of a space in my text but I'don't want to find a space from in a HTML tag.

"This is a string with <strong>some</strong> html in it"

The space that the regexp should find is the one between in and it. That regex is not so difficult. The same regex would also work here:

"This is a string with <strong>some</strong> html in <a href="">the end</a>"

The space would be now in the HTML between the and end (ok!)

But when my string is:

"This is a string with <strong>some</strong> html in the <a href="">end</a>"

Then the space should be between the and <a and not between <a and href="">end<a>.

Anyone some idea?

  • 写回答

1条回答 默认 最新

  • dongyao5843 2012-08-23 13:58
    关注

    Updating this answer since more information about requirements came to light.

    A combination of strip_tags(), strrpos(), substr() functions will do the trick. Use the strip_tags() function to clean out the HTML first. You'll then be left with the text and can explode it to find the last word, and then use strrpos() to find the position of that word in the original text.

    $stringToken = explode( ' ', strip_tags( $str ) );
    // Find the second-to-last word in the string.
    $word = $stringToken[ count( $string ) - 2 ];
    
    // Use $word to find its position within the original HTML-encoded string.
    $wordPosition = strrpos( $str, $word );
    
    if( $wordPosition !== false )
    {
        $finalSpace = strpos( $str, ' ', $wordPosition );
        $lastSpacePrefix = substr( $str, 0, $finalSpace );
        $lastSpaceSuffix = substr( $str, $finalSpace + 1 );
        $newStr = sprintf( "%s%s%s", $lastSpacePrefix, $finalSpaceSub, $lastSpaceSuffix );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了