Using preg_match to get filename
We use custom bbcode in our news posts
[newsImage]imageName.jpg[/newsImage]
And i'd like to use preg_match to get the imageName.jpg from between those tags. The whole post is stored in a variable called $newsPost.
I'm new to regex and I just can't figure 开发者_开发技巧out the right expression to use in preg_match to get what I want.
Any help is appreciated. Also, do any of you know a good resource for learning what each of the characters in regex do?
preg_match_all('/\[newsImage\]([^\[]+)\[\/newsImage\]/i', $newsPost, $images);
The variable $images
should then contain your list of matches.
http://www.php.net/manual/en/regexp.introduction.php
To answer your second question: A very good regex tutorial is regular-expressions.info.
Among other things, it also contains a regular expression syntax reference.
Since different regex flavors use a different syntax, you'll also want to look at the regex flavor comparison page.
As Rob said but escaping last ]
preg_match('/\[newsImage\]([^\[]+)\[newsImage\]/i', $newsPost, $images);
$images[1] will contain the name of image file.
This is not exactly what you asked for, but you can replace your [newsImage] tags with tags using the following code, its not perfect as it will fall down if you have an empty tag e.g. [newsImage][/newsImage]
function process_image_code($text) {
//regex looks for [newsImage]sometext[/newsImage]
$urlReg ="/((?:\[newsImage]{1}){1}.{1,}?(?:\[\/newsImage]){1})/i";
$pregResults = preg_split ($urlReg , $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$output = "";
//loop array to build the output string
for($i = 0; $i < sizeof($pregResults); $i++) {
//if the array item has a regex match process the result
if(preg_match($urlReg, $pregResults[$i]) ) {
$pregResults[$i] = preg_replace ("/(?:\[\/newsImage]){1}/i","\" alt=\"Image\" border=\"0\" />",$pregResults[$i] ,1);
// find if it has a http:// at the start of the image url
if(preg_match("/(?:\[newsImage]http:\/\/?){1}/i",$pregResults[$i])) {
$pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"",$pregResults[$i] ,1);
}else {
$pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"http://",$pregResults[$i] ,1);
}
$output .= $pregResults[$i];
}else {
$output .= $pregResults[$i];
}
}
return $output;
}
精彩评论