سؤال

consider the string

$tring = "e.g. i want to #sleep."

Am able to check for hash tags using

echo preg_replace('/(#\w+)/','<a href="tag.php?tag=\1">\1</a>',$tring']);

What i want to do is send the tag without the hash in front i.e. <a href="tag.php?tag=sleep">#sleep</a> instead of <a href="tag.php?tag=#sleep">#sleep</a>

هل كانت مفيدة؟

المحلول

You can modify your regex slightly to make this work properly.

echo preg_replace('/(#)(\w+)/i', '<a href="tag.php?tag=\2">\1\2</a>', $tring);

This creates two groupings, instead of the one that you had. Only the second group, the word, is used in the URL link. Both are used in the display test.

Examples of how this will work

e.g. i want to #sleep.   =>  e.g. i want to <a href="tag.php?tag=sleep">#sleep</a>.
this is a #cow           =>  this is a <a href="tag.php?tag=cow">#cow</a>
the #duck is #sleeping   =>  the <a href="tag.php?tag=duck">#duck</a> is <a href="tag.php?tag=sleeping">#sleeping</a>
#regex are @awesome #fun =>  <a href="tag.php?tag=regex">#regex</a> are @awesome <a href="tag.php?tag=fun">#fun</a>

As you can see, this handles multiple tags in the string as well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top