David19801
David19801

Reputation: 11448

Make a regex upto the end of the string?

I have:

$string='#229: Tomato Soup Menu';
preg_match_all('/: (.+?)*/', $string , $arr);

I'm trying to make the return just "Tomato Soup Menu". That is everything after the colon space, until the end of the string.

Any ideas?

Upvotes: 1

Views: 85

Answers (3)

hakre
hakre

Reputation: 198203

The regular expressions of sscanf­Docs are normally easier to grasp and the function allows you to directly assign the value to a variable:

$string='#229: Tomato Soup Menu';
$r = sscanf($string, "#%*d: %[^\n]", $return);
echo $return;

This will output Tomato Soup Menu, see Demo.

If you prefer PCRE syntax, the $ character matches the end of a string (or end of line in multiline-mode).

$string='#229: Tomato Soup Menu';
preg_match_all('/: (.*)$/', $string , $arr);

The . character does not match end of line anyway in standard mode, so you can even more simplify your pattern:

$string='#229: Tomato Soup Menu';
preg_match_all('/: (.*)/', $string , $arr);

Upvotes: 2

Dave Child
Dave Child

Reputation: 7901

Try this (it assumes that the format is always consistent at the start - a pound symbol, then numbers, then a colon, then a space, then the text you want):

$string='#229: Tomato Soup Menu';
$text = preg_replace('/^#[0-9]+: (.+)/', '$1', $string);

If it's just everything after the colon-space, and the start isn't consistent, try this:

$string='#229: Tomato Soup Menu';
$text = preg_replace('/^(.*?): (.+)/', '$2', $string);

Upvotes: 1

Andomar
Andomar

Reputation: 238246

You're using a non-greedy regex:

(.+?)*

This tries to match as little as possible, which for this expression is always nothing. Try the non-greedy equivalent instead:

: (.+)

Upvotes: 3

Related Questions