Yuseferi
Yuseferi

Reputation: 8700

replace all <a> tag to some character in php

I want to replace <a></a> to [] in php, as example if I have :

This is sample test to say you <a href="nowhere/333" id="blabah" > help</a> and you can redirect me to <a href="dddd">answer</a>

I want it replaced to

This is sample test to say you [help] and you can redirect me to [answer],

How can I achieve this job in php with regex?

Upvotes: 0

Views: 113

Answers (3)

Use a Document Object Model and avoid regular expressions to parse HTML at all costs.

echo "[".$dom->getElementsByTagName('a')->item(0)->nodeValue."]";

Demo

The code.. (for the edited question)

<?php
$html='This is sample test to say you  <a href="nowhere/333" id="blabah" > help</a> and  you can redirect me to <a href="dddd">answer</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$srch=array();$rep=array();
foreach($dom->getElementsByTagName('a') as $atag)
{
   $srch[]=trim($atag->nodeValue);
   $rep[]="[".trim($atag->nodeValue)."]";
}

echo str_replace($srch,$rep,strip_tags($html));

OUTPUT :

This is sample test to say you   [help] and  you can redirect me to [answer]

Upvotes: 7

stealthyninja
stealthyninja

Reputation: 10371

Answer should go to Shankar Damodaran, this is his answer extended to meet the OP's requirements:

<?php
$html  = 'This is sample test to say you  <a href="nowhere/333" ';
$html .= 'id="blabah" > help</a> and  you can redirect me to <a ';
$html .= 'href="dddd">answer</a> it replaced to';

$dom = new DOMDocument;
$dom->loadHTML($html);

$elements = count($dom->getElementsByTagName('a'));

for ($i = 0; $i <= $elements; $i++) {
    echo "[" . trim($dom->getElementsByTagName('a')->item($i)->nodeValue) . "]";
}
?>

Extended Demo

Upvotes: 1

aelor
aelor

Reputation: 11116

search <a.*?>(.*?)<\/a> and replace with [\1]

<?php
$html='<a href="nowhere/333" id="blabah" > help</a>';
echo preg_replace('/<a.*?>(.*?)<\/a>/', '[\1]', $html);

Upvotes: 2

Related Questions