Welcome Guest, Not a member yet? Register   Sign In
Searching a string for a character and all the characters till the next whitespace?
#1

[eluser]kyleect[/eluser]
I've got a small micro blog app that I'm working on and I'm trying to implement a new feature, tags. The tags use the following syntax "#tag" and are plain text inside the post. When I display these posts, I need to search through the post, find these tags and hyperlink them. I know I need to use Regex but it starts to get a bit fuzzy past that. Can someone point me in the right direction as far as the function I need to look at and some advice on where to start with the regex search string? I'm using PHP5. Thanks!
#2

[eluser]sophistry[/eluser]
happy birthday! here's a present for you...

preg_replace() is the function you need.

regex pattern for the preg_replace() function (assumes whitespace before pound sign #):
Code:
'/#([a-z0-9]+)\s/i'

replacement:
Code:
'<a href="http://example.com/tags/$1">$1</a>'

give that a try.

EDIT: added i switch to the regex pattern to make it case insensitive.
#3

[eluser]kyleect[/eluser]
Thanks for the reply and answer. Ok, I tried this but it didn't work. Here is the exact code I'm using:

Code:
&lt;?php
    echo nl2br(preg_replace('/#([a-z0-9])\s/i', '<a href="$1">$1</a>', $post['body']));
?&gt;

$post['body'] contains the following:

Code:
test test test

#test_post

It didn't generate any errors but didn't create the hyperlink either. Can you see anything I'm doing incorrectly?
#4

[eluser]sophistry[/eluser]
yes. the regex doesn't allow for underscore. add an underscore character just before a-z

Code:
echo nl2br(preg_replace('/#([_a-z0-9])\s/i', '<a href="$1">$1</a>', $post['body']));
#5

[eluser]kyleect[/eluser]
Tried that and got same result
#6

[eluser]kyleect[/eluser]
This is what I'm testing with:

Code:
&lt;?php
    $string = "test test test #test_post";
    
    echo preg_replace('/#([_a-z0-9])\s/i', '<a href="$1">$1</a>', $string);
?&gt;
#7

[eluser]sophistry[/eluser]
you dropped the plus sign. see the original regex post i made - there is a plus sign after the character class.

also, i changed the \s to a \b to allow the tag to be at the end of the string. \s would require the tag to have a space character. \b makes it so the regex pattern can complete even if there is a linebreak or end of string.

Code:
echo preg_replace('/#([_a-z0-9]+)\b/i', '<a href="$1">$1</a>', $string);

cheers.
#8

[eluser]kyleect[/eluser]
Thanks!




Theme © iAndrew 2016 - Forum software by © MyBB