PHP截断特定句子结尾的字符串结尾

时间:2014-09-19 15:44:54

标签: php regex string search

我有一个字符串

$description = 'Front: 1 1/2" W x 1" H ... Back: 2 1/4" W x 1 1/4" H Standard Imprint Area is the front. Optional Imprint Area is the back. Imprint on Standard Location Unless Otherwise Specified on Order. For Printing on Both Positions, Add $40.00(G) Set Up Plus .25(G) Per Piece.'

我需要将字符串修剪为包含文本的句子" Optional Imprint"作为最后一句话。

因此,如果文本包含"可选版本说明",请找到句子的结尾,并丢弃其结尾点后的所有字符,期间 )。

上面例子中我需要的是:

$description = 'Front: 1 1/2" W x 1" H ... Back: 2 1/4" W x 1 1/4" H Standard Imprint Area is the front. Optional Imprint Area is the back.'

3 个答案:

答案 0 :(得分:1)

以下正则表达式会匹配从开头到字符串Optional Imprint的所有字符以及以下字符到第一个点。

^.*Optional Imprint[^.]*\.

DEMO

$description = 'Front: 1 1/2" W x 1" H ... Back: 2 1/4" W x 1 1/4" H Standard Imprint Area is the front. Optional Imprint Area is the back. Imprint on Standard Location Unless Otherwise Specified on Order. For Printing on Both Positions, Add $40.00(G) Set Up Plus .25(G) Per Piece.';
$regex = '~^.*Optional Imprint[^.]*\.~';
if (preg_match($regex, $description, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }

<强>输出:

Front: 1 1/2" W x 1" H ... Back: 2 1/4" W x 1 1/4" H Standard Imprint Area is the front. Optional Imprint Area is the back.

答案 1 :(得分:1)

您可以使用preg_match()功能:

if (preg_match('/.*Optional Imprint.*\./U', $description, $match))
    echo $newDescription = $match[0];
else {
    $newDescription = '';
    echo 'no match';
}

U选项是非贪婪选项。这意味着正则表达式将匹配最少的字符。

答案 2 :(得分:0)

您可以将单词和句点用作分隔符。

$first_block = explode('Optional Imprint', $description);
$last_sentence = explode('.', $first_block[1]);
$description = $first_block  . 'Optional Imprint' . $last_sentence . '.';