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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭