Jump to content

Preg_match


plznty

Recommended Posts

How can I preg_match the alt value for each of these?

Thanks in advance.

<li><img src="yes/0.bmp" alt="0" /></li>

<li><img src="yes/7.bmp" alt="7" /></li>

<li><img src="yes/0.bmp" alt="0" /></li>

<li><img src="yes/4.bmp" alt="4" /></li>

<li><img src="yes/0.bmp" alt="0" /></li>

<li><img src="yes/0.bmp" alt="0" /></li>

<li><img src="yes/0.bmp" alt="0" /></li>

Link to comment
Share on other sites

$tag = "<img src=\"yes/0.bmp\" alt=\"1\" />";
$matches = array();
echo preg_match("/alt=\"[0-9]{1,2}\"/", $tag, $matches);
echo '<pre>';
print_r($matches)
echo '</pre>';

 

That worked for me, only registers alts that are in the range of 1-2 characters, ie up to 99, though that can easily be changed in the expression.

 

Returns:

alt="1"

Link to comment
Share on other sites

Another way would be this:

 


$html = '

<li><img src="yes/0.bmp" alt="0" /></li>
<li><img src="yes/7.bmp" alt="7" /></li>
<li><img src="yes/0.bmp" alt="0" /></li>
<li><img src="yes/4.bmp" alt="4" /></li>
<li><img src="yes/0.bmp" alt="0" /></li>
<li><img src="yes/0.bmp" alt="0" /></li>
<li><img src="yes/0.bmp" alt="0" /></li> 

';

preg_match_all("/alt=\"(.*?)\"/", $html, $matches);

var_dump($matches);

 

..which outputs...

 

array
  0 => 
    array
      0 => string 'alt="0"' (length=7)
      1 => string 'alt="7"' (length=7)
      2 => string 'alt="0"' (length=7)
      3 => string 'alt="4"' (length=7)
      4 => string 'alt="0"' (length=7)
      5 => string 'alt="0"' (length=7)
      6 => string 'alt="0"' (length=7)
  1 => 
    array
      0 => string '0' (length=1)
      1 => string '7' (length=1)
      2 => string '0' (length=1)
      3 => string '4' (length=1)
      4 => string '0' (length=1)
      5 => string '0' (length=1)
      6 => string '0' (length=1)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.