数组内的Preg_split语句保持标点符号

时间:2011-11-05 00:56:53

标签: php regex arrays

我有这样的文字: “这是句子1.这句话是2.这句话3?你好世界!”

我使用此代码将文本拆分为句子并将其插入数组中。

 $content = $page_data->post_content;
   $sentence = preg_split('/[!?\.]\s?/', $content);
   $sentence = array_map('trim', $sentence);
   echo $sentence[0]; - **which renders this is sentence 1 - without the "."**
   ....

如何使用此代码并保留标点符号?

泰:)

2 个答案:

答案 0 :(得分:0)

preg_split没有这样的标志,它保留了分隔符,但是,你可以使用preg_match_all:

<?php

    $content = "this is sentence 1. this is sentence 2. is this sentence 3? hello world!";
    preg_match_all('/([^\.\?!]+[\.\?!])/', $content, $sentence);
    $sentence = array_map('trim', $sentence[0]);
    print_r($sentence);

?>

答案 1 :(得分:0)

你可以使用断言背后的正面看法:

$sentence = preg_split('/(?<=[!?.])./', $content);

See it