regex - how to replace a string into an anchor tag in php -
i having of problem on how replace text anchor tag in text has text similar in href property of tag.
the text should display below:
//input $string = "text1 text2 text23 text24"; $tofind = "text2"; //output <a href="welcome_to_text2.php">text2</a>
i used code below wrong output:
<?php $fulltext = "text1 text2 text23 text24"; $tofind = "text2"; $string = explode(" " , $str); foreach($string $value){ $href = "welcome_to_{$tofing}.php"; $fulltext = preg_replace('/('.preg_quote($tofind, '/').')/i', "<a href=\"{$href}\">"."\\1"."</a>", $fulltext ); } echo $fulltext ; //it outputs <a href="welcome_to_<a href=""">text2</a> ?>
text23 , text24 replaced since text2 occurs on both string. want replace text2 alone since matched. know? thanks
you can use code below:
$fulltext = "text1 text2 text23 text24"; $tofind = "text2"; $array = explode(" " , $fulltext); $filekey = array_search($tofind, $array); // if giving file not exist use 'text1' default. $filename = isset($array[$filekey]) ? $array[$filekey] : 'text1'; echo sprintf('<a href="welcome_to_%s.php">%s</a>', $filename, $filename);
or if want build links elements in array:
$fulltext = "text1 text2 text23 text24"; $tofind = "text2"; $array = explode(" " , $fulltext); $text = ''; foreach ($array $value) { $text .= sprintf('<a href="welcome_to_%s.php">%s</a><br />', $value, $value); } echo $text;
hope helps.
Comments
Post a Comment