Khalid Askia
Khalid Askia

Reputation: 33

PHP : add a html tag around specifc words

I have a data base with texts and in each text there are words (tags) that start with # (example of a record : "Hi I'm posting an #issue on #Stackoverflow ")

I'm trying to find a solution to add html code to transform each tag into a link when printing the text.

So the text are stored as strings in MySQL database like this :

Some text #tag1 text #tag2 ...

I want to replace all these #abcd with

<a href="targetpage.php?val=abcd">#abcd</a>

And have a final result as follow:

Some text <a href="targetpage.php?val=tag1">#tag1</a> text <a href="targetpage.php?val=tag2">#tag2</a> ...

I guess that i should use some regex but it is not at all my strong side.

Upvotes: 2

Views: 3376

Answers (3)

Er. Amit Joshi
Er. Amit Joshi

Reputation: 645

Try this the function

<?php
  $demoString1 = "THIS is #test STRING WITH #abcd";
  $demoString2 = "Hi I'm posting an #issue on #Stackoverflow";

  function wrapWithAnchor($link,$string){
       $pattern = "/#([a-zA-Z0-9]+)/";
       $replace_with = '<a href="'.$link.'?val=$1">$1<a>';

       return preg_replace( $pattern, $replace_with ,$string ); 
 }

   $link= 'http://www.targetpage.php';
   echo wrapWithAnchor($link,$demoString1);
   echo '<hr />';
   echo wrapWithAnchor($link,$demoString2);

 ?>

enter image description here

enter image description here

Upvotes: 1

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

Try the following using preg_replace(..)

$input = "Hi I'm posting an #issue on #Stackoverflow";
echo preg_replace("/#([a-zA-Z0-9]+)/", "<a href='targetpage.php?val=$1'>#$1</a>", $input);

http://php.net/manual/en/function.preg-replace.php

Upvotes: 2

wp78de
wp78de

Reputation: 18950

A simple solution could look like this:

$re = '/\S*#(\[[^\]]+\]|\S+)/m';
$str = 'Some text #tag1 text #tag2 ...';
$subst = '<a href="targetpage.php?val=$1">#$1</a>';

$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;

Demo

If you are actually after Twitter hashtags and want to go crazy take a look here how it is done in Java.

There is also a JavaScript Twitter library that makes things very easy.

Upvotes: 1

Related Questions