0

I have a string

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

I need to trim the string to one that has the sentence which contains the text "Optional Imprint" as the last sentence.

So, if the text contains "Optional Imprint", find the end of the sentence, and discard all characters after it's ending point, the period(.).

What I would need returned from the above example is:

$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.'
Angelo
  • 417
  • 6
  • 18
  • Do you always want it to trim after the second period? Can this text be dynamic? Provide a little more details. – Sean Keane Sep 19 '14 at 15:49

3 Answers3

1

The below regex would match all the characters from the start to the string Optional Imprint plus the following chars upto the first dot.

^.*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;
    }

Output:

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.
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
1

You can use the function preg_match():

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

The U option is the non-greedy option. It means that the regex will match a minimum of characters.

Adam Sinclair
  • 1,644
  • 10
  • 15
0

You can use the words and period as delimiters.

$first_block = explode('Optional Imprint', $description);
$last_sentence = explode('.', $first_block[1]);
$description = $first_block  . 'Optional Imprint' . $last_sentence . '.';
Brent Baisley
  • 12,441
  • 2
  • 21
  • 39