Adam Ramadhan
Adam Ramadhan

Reputation: 22810

get a string before the first "." with php

"Lorem Ipsum is simply dummy text of the printing and typesetting industry."

from

"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

how can we do that ? is there a good function in php for doing things like this ?

Thanks

Adam Ramadhan

Upvotes: 2

Views: 1507

Answers (5)

Mr Griever
Mr Griever

Reputation: 4023

For PHP 5.3 and later you could use the before_needle argument with strstr:

strstr( $youstringhere, ".", true );

Upvotes: 5

Silver Light
Silver Light

Reputation: 45912

// fastest way
echo substr($text, 0, strpos('.', $text));

Upvotes: 4

Pascal MARTIN
Pascal MARTIN

Reputation: 400972

What about something like this (others have suggested using explode -- so I'm suggesting another solution) :

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

if (preg_match('/^([^\.]*)/', $str, $matches)) {
    echo $matches[1] . '.';
}


The regex will :

  • Start at beginning of string : ^
  • Match anything that's not a . : [^\.]
  • Any number of times : [^\.]*

And, as you wanted a . at the end of the output and that . is not matched by the regex, you'll have to add it back when using what's been found by the regex.

Upvotes: 4

Michael Low
Michael Low

Reputation: 24506

You can split it using the explode() function.

$sentences = explode (".", $text);
// first sentence is in $sentences[0]

Upvotes: 4

stlvc
stlvc

Reputation: 823

You could use explode() to get the first sentence. http://de.php.net/manual/en/function.explode.php

Upvotes: 3

Related Questions