Page 1 of 1

What are the commas doing to me?!

Posted: Wed Dec 01, 2004 10:01 am
by primate
I am trying to allow people to use a code to enter URLs in a text area so that when its regurgitated the URL will be working correctly - similar to the way these forums work in effect. I have got this far:

Code: Select all

<?php
if ((strpos ($post, "[url]") !==FALSE AND strpos ($post, "[/url]") !==FALSE)) {			//convert URLs into working hyperlinks
		
		
		$data = strtok ($post, "]");
		while ($data) {
			
			if (strpos ($data, "http://") !==FALSE) {
				
				
				$data = substr ($data, 4);
				
				$unformatted_URLs = array ($data);      //create list of unformatted URLs in post 
				$formatted_URLs = array ('<a href="' . $data . '">' . $data . '</a>'); //convert each to a working URL
				
				}
				$data = strtok (" ");
			}
			
		$n = count ($unformatted_URLs);
		for ($x = 0; $x<$n; $x++) {  //now replace unformatted URL's with working URL's
	
		$post = str_replace ($unformatted_URLs[$x], $formatted_URLs[$x], $post);
		
		} 
		
		$post = str_replace ("[URL]", "", $post);
		$post = str_replace ("[/URL]", "", $post);
		
		}

?>
This seems to work OK unless there is a trailing , or . after the closing [/URL] in which case they , or . is included as part of the URL. Any suggestions as to why?

Posted: Wed Dec 01, 2004 12:22 pm
by protokol
I know you're trying to do this your own way, but I highly recommend using regular expressions for this kind of thing.

[php_man]preg_replace[/php_man]()
[php_man]preg_replace_callback[/php_man]()

Posted: Wed Dec 01, 2004 12:24 pm
by rehfeld
i tried your code and i see other problems.

the code is not working at all(for me) so i see no reason to worry about the commas and periods, yet.

it tried feeding this to it


Code: Select all

// EDIT- you cant see the [URL] tags below because this board stripped them
// both urls below have [URL] before them, and a closing url tag after them



$post = '

[url]http://foo.com[/url]

[url]http://foobar.com[/url].


';

and this was the result

Code: Select all

http&lt;a href="://foo.com

http://foobar.com.


"&gt;://foo.com

http://foobar.com.


&lt;/a&gt;
regex would likely be much better suited to this.
is there a reason you want to do it this way?
it can definately be done using strpos and something similar to what you have,
but regex would be easier. i dont have a regex pattern handy for this, but im sure google does, because all
message boards that use bbcode use regex for this

Posted: Tue Dec 07, 2004 9:34 am
by primate
Sorry for not responding sooner been working on other things. Thanks for the pointers, I will try out your suggestions.

I don't understand why you got that output rehfeld, at the very least you shold get the <a href bit on both URLs as this isn't reliant on any string manipulation. It does work for me though, except in the situation I posted about, nevertheless if there's a bettrer way to be doing it, I'd rather do it that way! :)