在php中获得前2个句子

时间:2016-03-09 15:38:14

标签: php explode preg-split

我们有这个代码可以抓住一个段落的前两个句子,除了它只计算句点的事实外,它完美无缺。即使它们有感叹号或问号,它也需要获得前两个句子。这就是我们目前使用的:

function createCustomDescription($string) {
  $strArray = explode('.',$string);
  $custom_desc = $strArray[0].'.';
  $custom_desc .= $strArray[1].'.';

  return htmlspecialchars($custom_desc);
}

如何检查问号和/或感叹号的任何想法?

4 个答案:

答案 0 :(得分:2)

function createCustomDescription($string) 
{

  $strArray  = preg_split('/(\.|\!|\?)/', $string, 3, PREG_SPLIT_DELIM_CAPTURE);      
  $strArray  = array_slice($strArray, 0, 4);

  return htmlspecialchars(implode('', $strArray));

}

答案 1 :(得分:2)

您可以将preg_split与正则表达式一起用于PREG_SPLIT_DELIM_CAPTURE选项所需的结尾,这将保留使用的标点符号。

function createCustomDescription($string) {
    $split = preg_split('/(\.|\!|\?)/', $string, 3, PREG_SPLIT_DELIM_CAPTURE);
    $custom_desc = implode('', array_slice($split, 0, 4));

    return htmlspecialchars($custom_desc);
}

答案 2 :(得分:1)

尝试使用此代码:

function createCustomDescription($string) {
    $strArray = preg_split( '/(\.|!|\?)/', $string);
    $custom_desc = $strArray[0].'.';
    $custom_desc .= $strArray[1].'.';

    return htmlspecialchars($custom_desc);
}

答案 3 :(得分:0)

首先全部替换?而且!完全停止(。)。然后使用您通常的代码 使用

public class MyExample extends ApplicationWindow {
  public MyExample() {
    super(null);
  }

  public void run() {
    setBlockOnOpen(true);
    open();
    Display.getCurrent().dispose();
  }

  @Override
  public int open() {
    // do some work
    if (...) {
      MessageDialog.openError(getShell(), "Error", "Error occured");
    }
    return super.open();
  }
}

然后使用您的代码以(。)

爆炸