2009-07-04 5 views
8

I've created this regexCómo reemplazar http: // o www con <a href.. in PHP

(www|http://)[^ ]+ 

that match every http://... or www.... but I dont know how to make preg_replace that would work, I've tried

preg_replace('/((www|http://)[^ ]+)/', '<a href="\1">\1</a>', $str); 

but it doesn't work, the result is empty string.

+0

Dup: http://stackoverflow.com/ questions/507436/how-do-i-linkify-urls-in-a-string-with-php –

Respuesta

14

You need to escape the slashes in the regex because you are using slashes as the delimiter. You could also use another symbol as the delimiter.

// escaped 
preg_replace('/((www|http:\/\/)[^ ]+)/', '<a href="\1">\1</a>', $str); 

// another delimiter, '@' 
preg_replace('@((www|http://)[^ ]+)@', '<a href="\1">\1</a>', $str); 
+2

¡Felicitaciones! Eres el único que no copia la expresión regular incorrecta del caos. – Gumbo

+1

No agrega automáticamente http: // antes de www, por lo que no es del todo correcto: www.google.com se convertirá en ... instead of

1
preg_replace('!((?:www|http://)[^ ]+)!', '<a href="\1">\1</a>', $str); 

When you use / as your pattern delimiter, having / inside your pattern will not work out well. I solved this by using ! as the pattern delimiter, but you could escape your slashes with backslashes instead.

I also didn't see any reason why you were doing two paren captures, so I removed one of them.

Part of the trouble in your situation is that you're running with warnings suppressed; if you had error_reporting(E_ALL) on, you'd have seen the messages PHP is trying to generate about your delimiter problem in your regex.

+0

Es curioso que la mayoría haya usado su expresión regular incorrecta para sus ejemplos. – Gumbo

+0

Imagino que todos estábamos copiando OP's. Solucionado ahora, en cualquier caso. – chaos

1

Your main problem seems to be that you are putting everything in parentheses, so it doesn't know what "\1" is. Also, you need to escape the "/". So try this:

preg_replace('/(www|http:\/\/[^ ]+)/', '<a href="\1">\1</a>', $str);

Edit: It actually seems the parentheses were not an issue, I misread it. The escaping was still an issue as others also pointed out. Either solution should work.

+0

Me gustaría agregar que las referencias anteriores están numeradas por el paréntesis de apertura. Por ejemplo, en la expresión regular "T (e (st))", \ 1 contiene "est" y \ 2 contiene "st". –

2

When using the regex codes provided by the other users, be sure to add the "i" flag to enable case-insensitivity, so it'll work with both HTTP:// and http://. For example, using chaos's code:

preg_replace('!(www|http://[^ ]+)!i', '<a href="\1">\1</a>', $str); 
2

First of all, you need to escape—or even better, replace—the delimeters as explained in the other answers.

preg_replace('~((www|http://)[^ ]+)~', '<a href="\1">\1</a>', $str); 

Secondly, to further improve the regex, the $n replacement reference syntax is preferred over \\n, as stated in the manual.

preg_replace('~((www|http://)[^ ]+)~', '<a href="$1">$1</a>', $str); 

En tercer lugar, utiliza innecesariamente paréntesis de captura, lo que solo ralentiza las cosas. Deshazte de ellos. No se olvide de actualizar $1 a $0. En caso de que se lo pregunte, estos son paréntesis que no capturan: (?:).

preg_replace('~(?:www|http://)[^ ]+~', '<a href="$0">$0</a>', $str); 

Por último, me gustaría sustituir [^ ]+ con el más corto y más preciso \S, que es lo contrario de \s. Tenga en cuenta que [^ ]+ no permite espacios, ¡pero acepta nuevas líneas y pestañas! \S no.

preg_replace('~(?:www|http://)\S+~', '<a href="$0">$0</a>', $str); 
1

Si hay múltiples URL contenida en una cadena separada por un salto de línea en lugar de un espacio, usted tiene que utilizar el \ S

preg_replace('/((www|http:\/\/)\S+)/', '<a href="$1">$1</a>', $val); 
Cuestiones relacionadas