【问题标题】:In php how can i wrap a span tag around the last character?在 php 中,如何在最后一个字符周围加上 span 标签?
【发布时间】:2014-05-22 18:11:27
【问题描述】:

您好,我需要将字符串的最后一个字母包装在 span 标签中,我该如何在 php 中做到这一点?

例如:

$string = 'Get on the roller coaster';

应该输出:

'Get on the roller coaste<span>r</span>'

【问题讨论】:

  • O_o 为什么需要这样做?
  • 我想给最后一个字母上色,但不能控制 html,因为它是由 wordpress 动态创建的

标签: php regex str-replace


【解决方案1】:

找到

(.)$

替换为

<span>\1</span>

在这里演示:http://regex101.com/r/bY8kX0

像这样在 php 中:

<?php
$string = 'Get on the roller coaster';
echo preg_replace('/(.)$/', '<span>\1</span>', $string);

【讨论】:

    【解决方案2】:

    使用这个正则表达式:

    (.)$
    

    并将其替换为:

    <span>\1</span>
    

    . 表示字符,$ 表示结束,() 用于对字符进行分组以便使用。

    所以正则表达式说:匹配最后一个字符。

    我认为这是一个矫枉过正,会给出一个原生 php 答案,但是,我不知道 php :)

    感谢 sshashank124 的分组提示!

    【讨论】:

    • php 改用\1
    • 你可以使用$1\1替换模式,在PHP中也是如此。
    • @CasimiretHippolyte,谢谢伙计。所以我使用$1 应该没有问题?
    【解决方案3】:

    我可能会因为效率低下而受到抨击,但这里有一个替代方案:)

    // your string :)
    $string = 'Get on the roller coaster';
    
    // count the chars of your string, not the bytes ;)
    $stringLength = mb_strlen($string);
    
    // a string's characters can be accessed in array form IF it is an actual string and not an INT or w/e
    // echo $string[0] would produce the letter 'G'
    // so we want the last character, right-o!
    $wrapped = '<span>'.$string[($stringLength - 1)].'</span>';
    
    // mb_substr() the old string and give it that <span>-wrapped char
    $newString = mb_substr($string, 0, -1).$wrapped;
    
    // and presto!
    // $newString is now === Get on the roller coaste<span>r</span>
    

    【讨论】:

    • 这样更好,正则表达式更重,但使用mb_substr($string, 0, -1)
    • @Eun 谢谢!我只喝了 3 杯咖啡,现在已经快 10 点了,所以我想再喝一杯。那是一个伟大的 ol' DURRR 时刻 :)
    • 你甚至可以摆脱$stringLength
    • 那么使用这个例子比使用 aelor 的例子更好吗?正则表达式慢吗?
    • 是的,那会很酷。尽管出现未定义的错误,但我无法让这个示例工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多