19

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)
2
  • 1
    Could you give more examples of strings that you're trying to match? Commented Nov 26, 2012 at 2:57
  • sorry about the double backslash. i thought i need to put another backslash to make it visible. Commented Nov 27, 2012 at 6:39

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

preg_match("/(?<=#)[^#]*(?=#)/", $file, $match); works as well
could you please explain a just a little how that works? It is ok, but I can't understand that (?<=#) ... thank you.
@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 regular-expressions.info/lookaround.html
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?

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.