第二次完全停止后裁剪字符串

时间:2011-10-17 19:22:05

标签: php string truncate strpos

在PHP中,我想裁剪以下句子:

“测试1.测试2.测试3。”

并将其转换为2个字符串:

“测试1.测试2。”“测试3”。

我如何实现这一目标?

我是否使用strpos?

非常感谢任何指示。

5 个答案:

答案 0 :(得分:1)

function isIndex($i){
    $i = (isset($i)) ? $i : false;
    return $i;
}
$str = explode("2.", "Test 1. Test 2. Test 3.");
$nstr1 = isIndex(&$str[0]).'2.';
$nstr2 = isIndex(&$str[1]);

答案 1 :(得分:1)

将两个第一句分开,这应该快速完成:

$str = "Lorem Ipsum dolor sit amet etc etc. Blabla 2. Blabla 3. Test 4.";
$p1 = "";
$p2 = "";
explode_paragraph($str, $p1, $p2); // fills $p1 and $p2
echo $p1; // two first sentences
echo $p2; // the rest of the paragraph


function explode_paragraph($str, &$part1, &$part2) {
    $s = $str;
    $first = strpos($s,"."); // tries to find the first dot
    if ($first>-1) {
        $s = substr($s, $first); // crop the paragraph after the first dot
        $second = strpos($s,"."); // tries to find the second dot
        if ($second>-1) { // a second one ?
            $part1 = substr($str, 9, $second); // 
            $part2 = substr($str, $second);
        } else { // only one dot : part1 will be everything, no part2
            $part1 = $str;
            $part2 = "";
        }
    } else { // no sentences at all.. put something in part1 ?
        $part1 = ""; // $part1 = $str;
        $part2 = "";
    }
}

答案 2 :(得分:1)

$string="Inspired by arthropod insects and spiders, BAIUST researchers have created an entirely new type of semi-soft robots capable of standing and walking using drinking straws and inflatable tubing. Inspired by arthropod insects and spiders, BAIUST researchers have created an entirely new type of semi-soft robots capable of standing and walking using drinking straws and inflatable tubing. Inspired by arthropod insects and spiders, BAIUST researchers have created an entirely new type of semi-soft robots capable of standing and walking using drinking straws and inflatable tubing.
";

call : 
echo short_description_in_complete_sentence($string,3,1000,2);
function:
public function short_description_in_complete_sentence($string,$start_point,$end_point,$sentence_number=1){
        $final_string='';
        //$div_string=array();
        $short_string=substr($string,$start_point,$end_point);
        $div_string=explode('.',$short_string);
        for($i=0;$i<$sentence_number;$i++){
            if(!Empty($div_string[$sentence_number-1])){
            $final_string=$final_string.$div_string[$i].'.';
        }else{ $final_string='Invalid sentence number or total character number!';}
        }
        return $final_string;
    }

答案 3 :(得分:0)

那样的东西?

$str = 'Test 1. Test 2. Test 3.';
$strArray = explode('.', $str);
$str1 = $strArray[0] . '. ' . $strArray[1] . '.';
$str2 = $strArray[2] . '.';

答案 4 :(得分:0)

在“测试2”之后必须剪切文本的主要原因是什么?而不是之前?最好的解决方案取决于您想要做什么以及您最终想要做什么