【问题标题】:PHP Explode Show SeperatorPHP 爆炸显示分隔符
【发布时间】:2015-07-12 12:26:34
【问题描述】:

所以我编写了以下代码来显示句子中第四个句号/句点之后的单词。

$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;

   $minText = explode(".", $text);

   for($i = $limit; $i < count($minText); $i++){
       echo $minText[$i];
   }

该算法正在运行,它向我显示了第四个“。”之后的句子的其余部分。句号/句号....我的问题是输出没有在句子中显示句号,因此它只显示没有正确标点符号“。”的文本。 ....有人可以帮我解决如何修复代码以显示句号/句点吗?

非常感谢

【问题讨论】:

  • 您想查看单词之间存在的所有句点还是只查看末尾的句点?
  • 你能具体说明你需要什么以避免一些混乱吗?例如 - 你需要“separated.with.full.stops”吗?或“....separated.with.full.stops。”还是别的什么?

标签: php special-characters explode


【解决方案1】:

你可以试试这个……

    for($i = $limit; $i < count($minText); $i++){
       echo $minText[$i].".";
   }

注意在 echo 命令末尾添加的句点 // .".";

【讨论】:

  • 这解决了我的问题...作为魅力@superkayrad ;)
【解决方案2】:
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
    echo $minText[$i].".";
}

【讨论】:

    【解决方案3】:

    您可以使用 strpos() 函数通过更改 offset 参数找到分隔符 (.) 在字符串中的第 n 个位置,而不是拆分输入字符串然后对其进行迭代。

    那么,只需从我们刚刚确定的位置打印子字符串即可。

    <?php
    
    $text = "this.is.the.message.seperated.with.full.stops.";
    $limit = 4;
    $pos = 0;
    
    //find the position of 4th occurrence of dot 
    for($i = 0; $i < $limit; $i++) {
        $pos = strpos($text, '.', $pos) + 1;
    }
    
    print substr($text, $pos);
    

    【讨论】:

      【解决方案4】:

      如果所需的输出是“seperated.with.full.stops.”,那么您可以使用:

      <?php
      
      $text = "this.is.the.message.seperated.with.full.stops.";
      $limit = 4;
      
      $minText = explode(".", $text);
      $minText = array_slice($minText, $limit);
      
      echo implode('.', $minText) . '.';
      

      【讨论】:

        【解决方案5】:

        如果您想将单词之间的句点拆分,但将末尾的句点作为实际标点符号,您可能需要使用preg_replace() 将句点转换为另一个字符,然后将其分解。

        $text = "this.is.the.message.seperated.with.full.stops.";
        $limit = 4;
        
        //replace periods if they are follwed by a alphanumeric character
        $toSplit = preg_replace('/\.(?=\w)/', '#', $text);
        
           $minText = explode("#", $toSplit);
        
           for($i = $limit; $i < count($minText); $i++){
               echo $minText[$i] . "<br/>";
           }
        

        哪个产量

        seperated
        with
        full
        stops.
        

        当然,如果你只是想打印所有的句号,那么在你echo这个词之后添加它们。

        echo $minText[$i] . ".";
        

        【讨论】:

          猜你喜欢
          • 2011-06-24
          • 1970-01-01
          • 1970-01-01
          • 2011-02-21
          • 1970-01-01
          • 2016-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多