【问题标题】:php ellipsis, entire words for start and end with preg_replacephp省略号,以preg_replace开头和结尾的整个单词
【发布时间】:2013-12-17 09:58:38
【问题描述】:

尝试创建一个省略号,首先显示字符串的一部分,然后单击函数后显示字符串的其余部分。

找到了许多创建省略号函数的教程,但尝试了很长时间如何从结尾部分​​获取整个单词。

我试过这样做

<?php

    $text="Lorem ipsum dolor sit amet.";
    //     123456789
    echo substr($text,0,9); // result: "Lorem ips"
    echo '<hr>';

    $start = substr($text,0,9);
    // now this preg_replace() is awesome cause its only returning the entire word
    echo preg_replace('/\w+$/','',$start); //result: "Lorem"

    echo '<hr>';
    echo substr($text,9,strlen($text)); //result:  "um dolor sit amet."

    // now how should this preg_replace be to get result "ipsum dolor sit amet."

?>  

所以问题是:如何使用这个preg_replace() 来得到结果"ipsum dolor sit amet."

我尝试过更改 preg_replace('/\$+w/','',$start); 之类的内容,但我不知道如何编写该正则表达式。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:
    preg_replace('/^\w+\s/','',$text)
    

    【讨论】:

    • 太棒了,谢谢!你有任何链接或资源来学习如何编写这些正则表达式吗?
    • @caramba:要学习正则表达式,这是最好的教程之一:regular-expressions.info/tutorial.html
    【解决方案2】:

    Sorbos 的回答完全符合我的问题。由于我的问题不是很清楚,我不得不改变答案以获得我需要的结果。问题是字符串可能从任何地方开始(给定位置)。所以我仍然不知道这是否可以用 preg_replace() 解决

    这给了我同样的结果:

    $count=9;
    $rest = substr($text,$count,strlen($text));
    while( substr($rest, 0,1)!=' ' ) {
        $rest = substr($text,$count,strlen($text));
        $count--;
    }
    echo $rest;
    

    如果有人有更好的解决方案,请随时发布。 谢谢!

    【讨论】:

      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      相关资源
      最近更新 更多