【问题标题】:PHP truncate end of string at specific sentence endingPHP在特定句子结尾截断字符串的结尾
【发布时间】:2014-09-19 15:44:54
【问题描述】:

我有一个字符串

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

【问题讨论】:

  • 您是否总是希望它在第二个周期后修剪?这个文本可以是动态的吗?提供更多细节。

标签: php regex string search


【解决方案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.

【讨论】:

  • 谢谢你,最简单的方法
【解决方案2】:

可以使用preg_match()函数:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多