18

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)
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Kevin King
  • 557
  • 1
  • 9
  • 25

5 Answers5

32

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);
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
14

Use lookarounds:

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

Demo:

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

Output:

Array
(
    [0] => hello world
)

Test it here.

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 1
    `preg_match("/(?<=#)[^#]*(?=#)/", $file, $match);` works as well – Ωmega Jan 02 '15 at 18:41
  • could you please explain a just a little how that works? It is ok, but I can't understand that (?<=#) ... thank you. – Krzysztof Jarosz Jun 22 '16 at 22:36
  • @KrzysztofJarosz - `(?<=#)` is a positive lookbehind and means that match is preceded by `#`, while `(?=#)` is a positive lookahead and means that match is followed by `#`. For more information about lookaround zero-length assertions see http://www.regular-expressions.info/lookaround.html – Ωmega Jun 23 '16 at 13:26
0

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?

Sean Redmond
  • 3,974
  • 22
  • 28
0
preg_match('/1232#(.*)#$/', $file, $match);
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34
0

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# )