hi
I want to create a custom code and read the attributes.
[img src=“img.png” width=“11” alt=“adsfafsd”]
how would i create a regex that recognizes it and gives me the attributes in an array?
Thanks in advance.
Peanuts
hi
I want to create a custom code and read the attributes.
[img src=“img.png” width=“11” alt=“adsfafsd”]
how would i create a regex that recognizes it and gives me the attributes in an array?
Thanks in advance.
Peanuts
Do you mean with attribute names as keys?
$result['src']= "img.png";
$result['width'] = "11"; // string or integer or not bothered?
$result['alt'] = "adsfafsd";
Shame you are not starting with an xml-friendly string (eg xHTML):
$input = '<img src="img.png" width="11" alt="adsfafsd" />';
$out = simplexml_load_string($input);
var_dump($out);
// gives
object(SimpleXMLElement)[1]
public '@attributes' =>
array
'src' => string 'img.png' (length=7)
'width' => string '11' (length=2)
'alt' => string 'adsfafsd' (length=8)
thanks so far.
I can’t use the xml codes i did look into it but there are constraints ;(
yeah the second post about the results is spot on. i’m not worried about datatypes i can manage that after it’s in the array.
Could you try the following code?
$s = '[img src="img.png" width="11" alt="adsfafsd"] test [img src="img.jpg" width="22" alt="hi"]';
$pattern = '#\\[img([^\\]]+)\\]#si';
if (preg_match_all($pattern, $s, $m))
{
$pattern = '#(\\w+="[^"]+")#i';
$attributes = array();
foreach($m[1] as $m1)
{
if (preg_match_all($pattern, $m1, $attrm))
{
foreach($attrm as $v)
{
$tmp = array();
foreach($v as $vv)
{
$t = explode("=", $vv);
$tmp[trim($t[0])] = str_replace('"', '', $t[1]);
}
}
$attributes[] = $tmp;
}
}
print_r($attributes);
}
although it looks good… it’s not working.
hi … i’ve changed some of this.
and the first step is working the problem is that the second pattern isn’t picking anything up. i want to find the different attributes. in now is 1 string with all the attributes.
$pattern = '#\\\\[img([^\\]]+)\\]#smi';
if (preg_match_all($pattern, $content, $m))
{
$pattern = '#(\\w+\\="[^\\"]+\\")#mi';
$pattern = '#\\"(?:[^\\\\"]+|\\\\.)*#mi';
$attributes = array();
foreach($m[1] as $m1)
{
if (preg_match_all($pattern, $m1, $attrm))
{
// there's nothing here..
foreach($attrm as $v)
{
$tmp = array();
foreach($v as $vv)
{
$t = explode("=", $vv);
$tmp[trim($t[0])] = str_replace('"', '', $t[1]);
}
}
$attributes[] = $tmp;
}
}
print_r($attributes);
}
Does the incoming string contain a single [*] tag, as in your first post, or does it contain multiples as in gvre’s example in #5 above?
Not sure what you mean there… the code I just posted is the latest i’m testing with …
I marked the point that it’s not getting too.
I had tested this code before I posted it here.
It matches one or more [img *] tags. Could you try it again?