Kevin King
Kevin King

Reputation: 567

PHP preg_match get in between string

I'm trying to get the string hello world.

This is what I've got so far:

$file = "1232#hello world#";

preg_match("#1232\#(.*)\##", $file, $match)

Upvotes: 19

Views: 59834

Answers (5)

Jevon McPherson
Jevon McPherson

Reputation: 39

What if you want the delimiter to also be included in the array, this would be more usefull for preg_split where you might not want each array element to begin and end with the delimiters, the example im about to show would would include the delimeters inside the array values. this would be what you would need preg_match('/\#(.*?)#/', $file, $match); print_r($match); this would output array( [0]=> #hello world# )

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270609

It is recommended to use a delimiter other than # since your string contains #, and a non-greedy (.*?) to capture the characters before #. Incidentally, # does not need to be escaped in the expression if it is not also the delimiter.

$file = "1232#hello world#";
preg_match('/1232#(.*?)#/', $file, $match);

var_dump($match);
// Prints:
array(2) {
  [0]=>
  string(17) "1232#hello world#"
  [1]=>
  string(11) "hello world"
}

Even better is to use [^#]+ (or * instead of + if characters may not be present) to match all characters up to the next #.

preg_match('/1232#([^#]+)#/', $file, $match);

Upvotes: 32

Ωmega
Ωmega

Reputation: 43673

Use lookarounds:

preg_match("/(?<=#).*?(?=#)/", $file, $match)

Demo:

preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
print_r($match)

Output:

Array
(
    [0] => hello world
)

Test it here.

Upvotes: 14

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

preg_match('/1232#(.*)#$/', $file, $match);

Upvotes: 0

Sean Redmond
Sean Redmond

Reputation: 4114

It looks to me like you just have to get $match[1]:

php > $file = "1232#hello world#";
php > preg_match("/1232\\#(.*)\\#/", $file, $match);
php > print_r($match);
Array
(
    [0] => 1232#hello world#
    [1] => hello world
)
php > print_r($match[1]);
hello world

Are you getting different results?

Upvotes: 0

Related Questions