问题
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)
回答1:
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);
回答2:
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:
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?
回答4:
preg_match('/1232#(.*)#$/', $file, $match);
回答5:
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#
)
来源:https://stackoverflow.com/questions/13557894/php-preg-match-get-in-between-string