Answer the question
In order to leave comments, you need to log in
Regular expression error?
I want to split the line - so that the yurl is separate, the name is separate, the description is separate.
$content = '<img src="/image/fluffybunny.jpg" title="Тайтл" alt="Деск" />';
$image = preg_match_all('<img.*?(?:(?:\s+(src)="([^"]+)")|(?:\s+(title)="([^"]+)")|(?:\s+(alt)="([^"]+)")|(?:\s+[^\s]+))+.*/>', $content, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
echo "Адрес страницы: " . $matches[0][$i] . "\n";
echo "Название: " . $matches[1][$i] . "\n";
echo "Описание: " . $matches[3][$i] . "\n";
}
Answer the question
In order to leave comments, you need to log in
stackoverflow.com/questions/1732348/regex-match-op...
Use any available xml parser like simple_html_dom . With it, your design will be simple and readable:
foreach($html->find('img') as $img) {
echo "Адрес страницы: " . $img->src . "\n";
echo "Название: " . $img->title . "\n";
echo "Описание: " . $img->alt . "\n";
}
I am sincerely surprised by people who shove everything into one regular season. Parse <img(.*?)> separately and quietly extract src=\"(.*?)\" title=\"(.*?)\" from it
the last / was not escaped.
necessary \/
<img.*?(?:(?:\s+(src)="([^"]+)")|(?:\s+(title)="([^"]+)")|(?:\s+(alt)="([^"]+)")|(?:\s+[^\s]+))+.*\/>
Maybe like this?
$content = '<img src="/image/fluffybunny.jpg" title="Тайтл" alt="Деск" />';
function parse( $m )
{
print_r($m); // проверка
}
preg_replace_callback( '!<img.*src="([^"]+)".*title="([^"]+)".*alt="([^"]+)".*\>!us' , 'parse', $content );
your regex would be good to use like this:
for($i=1; $i< count($matches)-1; $i++){
$var = $matches[$i][0];
$$var = $matches[$i+1][0];
}
var_dump($src, $title, $alt);
When will programmers realize that it is too desirable to work with xml, html and other heresy like a tree, and not try to parse them with regular expressions, which are even unrealistic to understand the first time and which break if you add some insignificant nonsense to a valid tree structure .
Sorry, got...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('xdebug.var_display_max_depth', -1);
$string = '<img src="/image/fluffybunny.jpg" title="Тайтл" alt="Деск" />';
$array = (array) simplexml_load_string($string);
$attributes = $array['@attributes'];
var_dump($attributes);
// array(3) {
// 'src' =>
// string(22) "/image/fluffybunny.jpg"
// 'title' =>
// string(10) "Тайтл"
// 'alt' =>
// string(8) "Деск"
// }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question