khiemnn
khiemnn

Reputation: 115

PHP - Search string then delete until end of that string

I have a string like this:

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et ipsum ac tellus hendrerit semper in sit amet nulla.';

If found the string hendrerit semper, delete from that string until the end of that string.

The result should be:

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et ipsum ac tellus';

Can you guys guide me how to do it?

Thanks in advance!

Upvotes: 0

Views: 174

Answers (3)

matt
matt

Reputation: 367

Use substr and strpos. Note that you should always check the return value of strpos before using it further.

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et ipsum ac tellus hendrerit semper in sit amet nulla.';
$search = 'hendrerit semper';
if (strpos($string, $search) === false) {
    // $search not found in $string
    $result = false;
}
else {
    $result = substr($string, 0, strpos($string, $search));
}

Upvotes: 2

Jelmer Snoeck
Jelmer Snoeck

Reputation: 31

See PHP: strstr

Note that you have a 'before needle' parameter.

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et ipsum ac tellus hendrerit semper in sit amet nulla.';
echo strstr($string, 'hendrerit semper', true) . "\n";exit;

Will give you: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et ipsum ac tellus"

Upvotes: 0

Galen
Galen

Reputation: 30170

substring to get a substring and strpos to find the position

echo substr( $string, 0, strpos( $string, 'hendrerit semper' ) );

Upvotes: 4

Related Questions