Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replace... (i don't have good title 4 this) 3

Status
Not open for further replies.

iranor

Programmer
Joined
Jun 17, 2004
Messages
174
Location
CA
I don't want users to add html tags , so if I want to allow them to add links in their message I need a code.

To add a url in a message , the user would type : http://www.someurl.com

How can I change this in html tag when I output the message?

Like ,

http://www.someurl.com

would become (when user read message)

<a href= target=_blank>
How could I do that?
 
It is not a simple replace... If I posted here , it's that I searched but found nothing.

Anyone knows how to?
 
You'll probably want to take a look at preg_replace.

preg_replace() gives you the option of passing it an array of patterns and replacements. It can perform multiple changes to your message as necessary.

I recommmend, though, that you not perform the transformation at display time but rather at the time that you accept and store the message from the user. There is no point in performing the transformation every time the page is viewed when you can perform the transformation once and then let everyone view the transformed content. preg_replace() is very resource-intensive.



Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Regular expressions, as sleipnir214 says, are the solution. It's good for you to learn them because it's a powerful way to manipulate strings.
To change http://www.someurl.com:
Code:
$str = "[url]http://www.someurl.com[/url]";
#
$pattern = ('/\[url\](.*)\[\/url\]/');
$newStr = preg_replace($pattern,"<a href=\"$1\" target=\"_blank\">$1</a>",$str);
echo($newStr);
What does the pattern mean - it looks really cryptic:
/ opens the pattern
\[ the square bracket needs to be escaped since it has meta character meaning
url literal string
\] the closing bracket needs also escaping
( open a subpattern for capture
.* any number characters on a line
) close the subpattern
\[ escaped opening bracket for literal
\/ the forward slash needs to be escaped or it will end the pattern
url string literal
\] closing the literal
/ closing the pattern

In the replacement the new string is assembled and $1 is used to reference the first captured subpattern, in this case the url.
 
I have to say this is a blinding explanation, a star. Recommend FAQ'ing this DRJ478!

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top