Friday, May 21, 2010

How can I add a prefix to a php variable but only if it isn't already there?

I have a table in my database where I let people put their website. I read from the table and created an href off what they entered. If they enter it wrong I don't feel bad. But some people put http:// and some don't. Using php how can I say add http:// to the start of $my_website as long as its not there already?





dan

How can I add a prefix to a php variable but only if it isn't already there?
I'm not fluent in php so I'm assuming you will know the translation, you want to use an IndexOf function. .





if(my_website.IndexOf("http://") %26lt; 0 )


my_website = "http://"+my_website





alternatively you could use a RegEx expression, though again, the language barrier blocks me ;) I'm sure there's example code for it out there somewhere though.
Reply:Look, I'm not an expert in php, but I think I know the solution to your problem, there is a function in php called "substr"





you give this function a string and it cuts it as needed





for example:


substr(Hello, 1, 2) returns "el" . The first number indicates the letter to start the cutting after, the second number indicates the length of the cutting





substr(Hello, 2, 2) gives "ll"


substr(Hello, 1, 3) gives "ell"


substr(Hello, 0, 4) gives "Hell"





Now If we use this function in a combination with an If conditional, this should do the work, here is the code u should add:





if (substr($my_website, 0, 4) != http)


$my_website="http://" . $my_website





Notice the dot, it adds strings.


change this code to suite you as much as you like.


No comments:

Post a Comment