开发者

php preg_match_all backslash problem

I've got img tag in my text and I want to get the name of the file from src

So I use this code

preg_match_all("|\/img\/(.*)\/>|U", $article_header, $matches, PREG_PATTERN_ORDER);
echo "match=".$matches[1][0]."<br/>";

Doing so I get this as a 开发者_如何学Pythonresult

match=500.JPG\" alt=\"\" width=\"500\" height=\"360\"

So in this case I use "\/>" which means the end of tag.

But I want only name of the file "500.JPG" So I must use "\" but when I do it

    preg_match_all("|\/img\/(.*)\\|U", $article_header, $matches, PREG_PATTERN_ORDER);

I get no matches :( Please help

With the help of yes123 I did this

$doc = new DOMDocument();
$doc->loadHTML($article_header);

$imgs = $doc->getElementsByTagName('img');
$img_src = array();
foreach ($imgs as $img) {
// Store the img src
$img_src[] = $img->getAttribute('src');
echo $img_src[0];
}

which gives me this

\"sources/public/users/qqqqqq/articles/2011-06-11/7/img/500.JPG\"

But now anyway I want only 500.JPG from this

So what is the right regexp ?


To match a real backslash-char in regex, you have to 'double-escape' it, that means 4 backslashes to match a single backslash: \\\\

preg_match_all("|/img/(.*)\\\\|U", ...);


preg_match_all('/<img[^>*]src="([^"]+)".*>/Uis', $article_header, $matches)


You can't parse HTML with regex.

Use DOMDocument

// HTML already parsed into $dom
$imgs = $dom->getElementsByTagName('img');
$img_src = array();
foreach ($imgs as $img) {
  // Store the img src
  $img_src[] = $img->getAttribute('src');

}

Don't forget you can always search google or stackoverflow before opening a question


Try something like, I tested it now:

$article_header = 'foo <img src=\\"sources/public/users/qqqqqq/articles/2011-06-11/7/img/500.JPG\\" /> foo';
preg_match_all('|<img[^>]+?src="[^"]*?([^/"]+?)"|', stripslashes($article_header), $matches, PREG_PATTERN_ORDER);
echo "match=".$matches[1][0]."<br/>";

It seems that you have $article_header with slashes (that was a bit irritating), so I added an stripslashes().


use php function pathinfo

http://php.net/manual/en/function.pathinfo.php

pathinfo($img_src[0]);

result

Array
(
    [dirname] => sources/public/users/qqqqqq/articles/2011-06-11/7/img/
    [basename] => 500.JPG
    [extension] => JPG
    [filename] => 500
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜