Jump to content

Recommended Posts

There are many ways to delete everything after a character in a string. I am looking for a simple way to delete everything after a given word.

 

How about we retain everything before and including your desired word.  You can do something like this, although, a solution with string functions would be a bit better.

ini_set ("display_errors", "1");
error_reporting(E_ALL);

$subject = "I want everything before tim and nothing after";
$pattern = '/.* tim/';
preg_match($pattern, $subject, $matches);
print_r($matches);

?>

This is a brilliant solution, but it has a big problem: it does not work with line breaks. If even writing the php code in two lines as

$subject = "I want everything 
before tim and nothing after";
$pattern = '/.* tim/';
preg_match($pattern, $subject, $matches);
print_r($matches);

 

The result will be "before tim" not "I want everything before tim"

There you go, use jcbones's.  A solution utilizing string functions is better.

 

But just in case you were wondering, to make the regex solution work with multi lines you would change this line to

$pattern = '/(.|\s)* tim/m';

 

The 'm' modifier indicates, multiline and the pattern accepted one or more any char along with \s (any whitespace character [carriage return, line feed, space and tab]).

Something like:

<?php
$subject = "I want everything 
before tim and nothing after";
$word = 'tim';
$subject = substr($subject,0,(strpos($subject,$word) + strlen($word)));

echo $subject;
?>

 

$word should be defined like:

$word = ' tim ';

 

to prevent wrong result if the string is something like:

$subject = "I want everything in time 
before tim and nothing after";

 

right?

 

other option:

$subject = "I want everything in time 
before tim and nothing after";
$word = ' tim ';
$arr = explode($word, $string); 
echo $arr[0];   // if $word need to be ommited too  or

echo $arr[0] . $word;  // to include it

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.