【问题标题】:Replace part of string only the first time, WITH offset仅第一次替换字符串的一部分,带偏移量
【发布时间】:2013-10-14 14:40:18
【问题描述】:

我想解析一个文本文件,并将时间戳(如果存在)设置为彩色和粗体。基本上,文本可能如下所示:

15:40 - User1: hey
15:41 - User2: i was about to hit the road, but have at it
15:42 - User1: i was just wondering

现在,我在 \r\n 上爆炸(这已经很愚蠢了,因为行本身可能包含一个中断,但现在先把它放在一边),所以我用一个 foreach 循环来遍历它。

$string = explode("\r\n", $file);
foreach($string as $ex) {
    echo "<p>".$ex."</p>\r\n";
}

假设我想加粗整个时间戳,包括用户名。 str_replace 不起作用,因为 : 也在时间戳中。我的问题是,我如何将整个部分加粗?检查“ - ”的 strpos 给我留下了偏移量 5,但是如何将整个部分加粗直到下一个冒号出现? (同样,撇开人们的用户名可能有一个冒号)

见鬼,如果我自己能搞定,有没有可能将其更改为 $timestamp、$seperator、$user 和 $message?

亲切的问候,

韦斯利

【问题讨论】:

    标签: php str-replace explode strpos


    【解决方案1】:

    你最好在这里使用正则表达式:

    $bolded = preg_replace('/^\d+:\d+\s*-\s*[^:]+/', '<b>$1</b>', $ex);
    

    这匹配^\d+:\d+\s*-\s*[^:]+ 模式并将其替换为&lt;b&gt;$1&lt;/b&gt;,这实际上意味着匹配放置在粗体标签内(使用&lt;strong&gt; 以获得更多语义,这只是一个示例)。

    ^\d+:\d+\s*-\s*[^:]+ 匹配什么?

    ^      at the start of the string...
    \d+    one or more digits             -+
    :      a double colon                  +---> the time
    \d+    one or more digits             -+
    \s*    zero or more whitespace
    -      a dash
    \s*    zero or more whitespace
    [^:]+  one or more of "not :"         -----> the username
    

    【讨论】:

    • 非常感谢。精彩的解释。不过有一句话:1 美元应该是 0 美元! :)
    【解决方案2】:

    您可以将strpos()offset 一起使用:

    foreach($array as $value) {
        $needle = ':';
        $pos1 = strpos($value, $needle);
        $pos2 = strpos($value, $needle, $pos1 + strlen($needle));
        $bold = substr($value, 0, $pos2);
        $notBold = substr($value, $pos2);
        echo "<p><strong>$bold</strong>$notBold</p>";
    }
    

    Demo!

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2017-12-15
      • 2021-04-17
      相关资源
      最近更新 更多