Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd use a <a href="http://php.net/dom" rel="nofollow">DOM parser</a> instead of regex. Here's how:</p> <ul> <li>Load the HTML string using <a href="http://php.net/manual/en/domdocument.loadhtml.php" rel="nofollow"><code>loadHTML()</code></a></li> <li>Use <a href="http://php.net/manual/en/domdocument.getelementsbytagname.php" rel="nofollow"><code>getElementsByTagName()</code></a> to get all the images</li> <li>Loop through them and check if the image has an <code>alt</code> attribute. <ul> <li>If the image has an <code>alt</code> attribute, set the value of <code>$replacement</code> variable as the <code>alt</code> attribute. </li> <li>If the image doesn't have an <code>alt</code> attribute, set the <code>$replacement</code> to <code>(image)</code>. </li> </ul></li> <li>Use <a href="http://www.php.net/manual/en/domnode.replacechild.php" rel="nofollow"><code>replaceChild()</code></a> to replace the node with the newly created text node:</li> </ul> <p>Code:</p> <pre><code>$html = &lt;&lt;&lt;HTML Hi this is a photo of me &lt;img src='myself.jpg' alt='pic of me' /&gt; another pic of me &lt;img src='abc.jpg'/&gt; HTML; $dom = new DOMDocument; $dom-&gt;loadHTML($html); $images = $dom-&gt;getElementsByTagName('img'); $i = $images-&gt;length - 1; while ($i &gt; -1) { $node = $images-&gt;item($i); if ($node-&gt;hasAttribute('alt')) { $replacement = '('.$node-&gt;getAttribute('alt').')'; } else { $replacement = '(image)'; } $text = $dom-&gt;createTextNode($replacement."\n"); $node-&gt;parentNode-&gt;replaceChild($text, $node); $i--; } echo strip_tags($dom-&gt;saveHTML()); </code></pre> <p>Output:</p> <pre><code>Hi this is a photo of me (pic of me) another pic of me (image) </code></pre> <p><a href="https://eval.in/79670" rel="nofollow"><strong>Demo.</strong></a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload