Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取php中的前两个句子_Php_Explode_Preg Split - Fatal编程技术网

获取php中的前两个句子

获取php中的前两个句子,php,explode,preg-split,Php,Explode,Preg Split,我们有这样一个代码,它抓住了段落的前两句话,除了只计算句号之外,它工作得非常完美。它需要得到前两个句子,即使它们有感叹号或问号。这是我们目前正在使用的: function createCustomDescription($string) { $strArray = explode('.',$string); $custom_desc = $strArray[0].'.'; $custom_desc .= $strArray[1].'.'; return htmlspecialc

我们有这样一个代码,它抓住了段落的前两句话,除了只计算句号之外,它工作得非常完美。它需要得到前两个句子,即使它们有感叹号或问号。这是我们目前正在使用的:

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

  return htmlspecialchars($custom_desc);
}
您知道如何检查问号和/或感叹号吗?

尝试使用以下代码:

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

    return htmlspecialchars($custom_desc);
}

首先替换所有?还有!以句号(.)结束。然后使用您的常规代码 使用

然后,使用您的代码以(.)

进行分解,您可以使用正则表达式作为您想要的结尾,使用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);
}

这个可能的复制品工作得很好!保存标点符号正是我们想要的。非常感谢。伟大的看到MajicBob偷了我的密码。很高兴问题解决了。这是一个很好的解决方案,可以定位前两段的结尾,并用句点替换标点符号,但是,我们确实希望保留@MajicBob提出的现有标点符号。我意识到我在原来的帖子中没有提到这一点,但谢谢你的帮助!
function createCustomDescription($string) 
{

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

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

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

    return htmlspecialchars($custom_desc);
}