Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This was the best I could do using PHP's <a href="http://php.net/domdocument" rel="nofollow"><code>DOMDocument</code></a>.</p> <p> <pre><code>$str = '&lt;a href="http://my_domain_name.com/sports/info.php"&gt;&lt;img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" /&gt;Football sports news&lt;/a&gt;'; $doc = new DOMDocument(); $fragment = $doc-&gt;createDocumentFragment(); $fragment-&gt;appendXML( $str); $doc-&gt;appendChild( $fragment); // Create the &lt;span&gt; $node = $doc-&gt;createElement( 'span'); $node-&gt;setAttribute( 'style', 'color: #000000; background-color: #FFFF00; font-weight: normal;'); $node-&gt;nodeValue = 'sports'; foreach( $doc-&gt;getElementsByTagName( 'a') as $tag) { $img_tag = $tag-&gt;firstChild-&gt;cloneNode(); $text = $doc-&gt;createTextNode( $tag-&gt;textContent); $tag-&gt;nodeValue = ''; // Clear out the contents of the &lt;a&gt; // Get the text before and after the replacement $start = strpos( $text-&gt;wholeText, 'sports'); $before = $text-&gt;substringData( 0, $start); $after = $text-&gt;substringData( $start + strlen( 'sports'), strlen( $text-&gt;wholeText)); // Put the image tag back, along with the before text, the &lt;span&gt;, and the after text $tag-&gt;appendChild( $img_tag); $tag-&gt;appendChild( $doc-&gt;createTextNode( $before)); $tag-&gt;appendChild( $node); $tag-&gt;appendChild( $doc-&gt;createTextNode( $after)); } echo htmlentities( $doc-&gt;saveHTML()) . "\n"; </code></pre> <p>This outputs:</p> <pre><code>&lt;a href="http://my_domain_name.com/sports/info.php"&gt; &lt;img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news"&gt;Football &lt;span style="color: #000000; background-color: #FFFF00; font-weight: normal;"&gt;sports&lt;/span&gt; news &lt;/a&gt; </code></pre> <p><a href="http://codepad.viper-7.com/deZmRJ" rel="nofollow">Demo</a></p> <p>(You need PHP > 5.3)</p>
    singulars
    1. This table or related slice is empty.
    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. 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