Forum Moderators: coopster
$str = preg_replace('#([^\s]*)\¦(http://)([^\s]*)#', '<a href="\\2\\3">\\1</a>', $str);
from the php site and modified it just a bit, so now what it does is takes a string like "name¦http://www.google.com" and converts it to <a href="http://www.google.com">name</a>
I'm trying figure out how to do two more things with this regex though:
1. allow for link names with spaces by making the link name have a pipe on each side, like "¦name of link¦http://www.google.com"
2. linkify a url without a name defined, like make "http://www.google.com" turn into <a href="http://www.google.com">http://www.google.com</a>
1. allow for link names with spaces by making the link name have a pipe on each side, like "¦name of link¦http://www.google.com"
For this you can use a negative character set (see [devplanner.com ] ) to find things between pipes.
\¦([^\¦]*)\¦
Be aware code like this can run away from you if there is a stray pipe on your page, or if you mix the one-pipe and two-pipe syntax. You might want to limit the size of the match to, say 20 characters, like this:
\¦([^\¦]{0,20})\¦
2. linkify a url without a name defined, like make "http://www.google.com" turn into <a href="http://www.google.com">http://www.google.com</a>
([^\s]*)\¦ part should work pretty well to do this. But there are better URL matching patterns, e.g., I found a good perl regex tutorial and I'm starting to get the hang of it.
but I have a new perl regex question now...for a different project...and I'm not sure if it's even possible.
My string is a list of items and prices like:
bananas $3.29
remote $14.99
CD-Rs $10.00
where each item and associated price is seperated by a space and each item/price combo is seperated by a newline.
I'd like to use a regex to put those values in an array like:
array[0][0] = "bananas"
array[0][1] = "$3.29"
array[1][0] = "remote"
...etc
I don't see how to deal with the spaces and newlines though, keeping each price associated with the correct item.
Can it be done with regex, or is there another way?
'/([a-zA-Z0-9_\-]+) (\$[0-9]+\.[0-9]{0,2})/'
Would probably work.
You don't need to work about new lines, because regexps can be run either on the whole string, or one one-line at a time (which IIRC is the default). Also there is an option to make the regexp non-greedy, which roughly means it will match the smallest string possible.
Hope this helps.
It would be much faster and more efficient to just explode the string on the pipe and then stick the url into the href code via variable assignment.
You can accomplish the other things you mentioned with if statements.
Regular expressions are great, and for a few things they're indispensable... but in the majority of cases if you use built in PHP functions instead you won't find your scripts bogging down the server when/if they get a traffic spike.