2014-09-19 71 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選項是非貪婪的選項。這意味着正則表達式將匹配最少的字符。