Jump to content

Deleting after a given word in a string


etrader

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.