2014-09-19 112 views
0

我有一个字符串PHP截断结束

$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.' 

我需要字符串修剪一个具有包含文本“可选的印记”的最后一句句子。

所以,如果文本包含“可选印记”,找到句子的结尾,它的结束点之后抛弃所有的字符,该)。

我需要从上面的例子返回是:

$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.' 
+0

你是否总是希望它在第二阶段后修剪?这个文本可以动态吗?提供一点细节。 – 2014-09-19 15:49:54

回答

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. 
+0

谢谢你,最简单的方法 – Angelo 2014-09-19 16:04:29

0

您可以使用单词和周期作为分隔符。

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

可以使用功能preg_match()

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

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