2011-11-29 16 views

Respuesta

7

De esta manera:

if (preg_match('/(?<=net).*(?=\.php)/', $subject, $regs)) { 
    $result = $regs[0]; 
} 

Explicación:

" 
(?<=  # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) 
    net  # Match the characters “net” literally 
) 
.   # Match any single character that is not a line break character 
    *   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
(?=  # Assert that the regex below can be matched, starting at this position (positive lookahead) 
    \.  # Match the character “.” literally 
    php  # Match the characters “php” literally 
) 
" 
+0

Gracias FailedDev por la explicación detallada, que funciona perfectamente – silkAdmin

+3

''/ net (. *) \. Php /'', versión más simple, más corta (y posiblemente con mejor rendimiento) de la misma expresión. (Prefiero expresiones sin considerables innecesarios). – Qtax

2

Prueba esto:

preg_match("/net(.*)\.php$/","http://php.net/manual/en/function.preg-match.php", $matches); 
echo $matches[1]; 
// prints /manual/en/function.preg-match 
0

Este partido general de URLs le permite seleccionar partes de una URL:

if (preg_match('/\\b(?P<protocol>https?|ftp):\/\/(?P<domain>[-A-Z0-9.]+)(?P<file>\/[-A-Z0-9+&@#\/%=~_|!:,.;]*)?(?P<parameters>\\?[-A-Z0-9+&@#\/%=~_|!:,.;]*)?/i', $subject, $regs)) { 
    $result = $regs['file']; 
    //or you can append the $regs['parameters'] too 
} else { 
    $result = ""; 
} 
19

Una expresión regular puede no ser la herramienta más efectiva para este trabajo.

Intente utilizar parse_url(), combinado con pathinfo():

$url  = 'http://php.net/manual/en/function.preg-match.php'; 
$path  = parse_url($url, PHP_URL_PATH); 
$pathinfo = pathinfo($path); 

echo $pathinfo['dirname'], '/', $pathinfo['filename']; 

Las salidas de código anteriores:

/manual/en/function.preg-match
+0

Gracias phoenix, eso también funciona, pero yo estaba buscando una solución reg ex para esto. – silkAdmin

+1

@silkAdmin Eso es curioso; ¿Por qué la solución debe ser una expresión regular? –

+1

Lo siento, no debería haber usado la etiqueta PHP que era confusa, necesitaba la expresión regular para un archivo de configuración de Nginx donde su solución no es una opción – silkAdmin

-1

expresiones regulares para hacer coincidir todo después de "red" y antes de ".php":

$pattern = "net([a-zA-Z0-9_]*)\.php"; 

En la expresión regular anterior, puede encontrar el grupo de caracteres coincidente encerrado por "()" para ser lo que está buscando.

Espero que sea útil.

+2

Eso no coincidirá con el ejemplo dado, porque hay un punto en él: 'function.preg-match' – Toto

+0

Por no mencionar que no coincide con las barras inclinadas, tampoco. Además, la expresión regular no está anclada, lo que probablemente no cause problemas (el operador '*' es codicioso por defecto), pero no es una buena práctica. –

2

No es necesario utilizar una expresión regular para diseccionar una URL. PHP tiene funciones incorporadas para esto, pathinfo() y parse_url().

0

Aquí es una solución de expresiones regulares mejor que lo que la mayoría han proporcionado hasta ahora, si me preguntas: http://regex101.com/r/nQ8rH5

 
/http:\/\/[^\/]+\K.*(?=\.[^.]+$)/i 
0

simple:

$url = "http://php.net/manual/en/function.preg-match.php"; 
preg_match("/http:\/\/php\.net(.+)\.php/", $url, $matches); 
echo $matches[1]; 

$matches[0] es su URL completa, $matches[1] es la parte que se querer.

Ver mismo: http://codepad.viper-7.com/hHmwI2

1

Sólo por el gusto de hacerlo, aquí hay dos maneras que no han sido exploradas:

substr($url, strpos($s, '/', 8), -4) 

O:

substr($s, strpos($s, '/', 8), -strlen($s) + strrpos($s, '.')) 

basa en la idea de que Los esquemas HTTP http:// y https:// tienen como máximo 8 caracteres, por lo que, por lo general, es suficiente encontrar la primera barra oblicua desde la 9na posición en adelante. Si la extensión es siempre .php, el primer código funcionará; de lo contrario, se requiere el otro código.

Para una solución de expresión regular puro se puede romper la cadena abajo como este:

~^(?:[^:/?#]+:)?(?://[^/?#]*)?([^?#]*)~ 
          ^

La porción camino sería en el interior del grupo primera memoria (es decir, índice 1), indicado por el ^ en la línea debajo la expresion. La eliminación de la extensión se puede hacer usando pathinfo():

$parts = pathinfo($matches[1]); 
echo $parts['dirname'] . '/' . $parts['filename']; 

También puede modificar la expresión a esto:

([^?#]*?)(?:\.[^?#]*)?(?:\?|$) 

Esta expresión no es muy óptimo, sin embargo, debido a que tiene algunas volver seguimiento en ella. Al final me quedo con algo menos de encargo:

$parts = pathinfo(parse_url($url, PHP_URL_PATH)); 
echo $parts['dirname'] . '/' . $parts['filename']; 
0

| (? < = \ w) /.+ (?. = \ \ W + $) |

  • seleccionar todo, desde el primer literal '/' precedido por
  • mirada detrás de un (\ w) Predictivo
  • hasta seguida de una mirada hacia el futuro
    • literal '' anexado por
    • una o más palabras (\ w) caracteres
    • antes de que finalice $
 
    re> |(?<=\w)/.+(?=\.\w+$)| 
Compile time 0.0011 milliseconds 
Memory allocation (code space): 32 
    Study time 0.0002 milliseconds 
Capturing subpattern count = 0 
No options 
First char = '/' 
No need char 
Max lookbehind = 1 
Subject length lower bound = 2 
No set of starting bytes 
data> http://php.net/manual/en/function.preg-match.php 
Execute time 0.0007 milliseconds 
0: /manual/en/function.preg-match 

|. // [^ /] * (. *) \ \ w + $ |

  • encontrar dos literal '//' seguido de cualquier cosa menos un literal '/'
  • seleccionar todo hasta
  • encuentran literal '' seguido de la única Palabra \ w caracteres antes del final $
 
    re> |//[^/]*(.*)\.\w+$| 
Compile time 0.0010 milliseconds 
Memory allocation (code space): 28 
    Study time 0.0002 milliseconds 
Capturing subpattern count = 1 
No options 
First char = '/' 
Need char = '.' 
Subject length lower bound = 4 
No set of starting bytes 
data> http://php.net/manual/en/function.preg-match.php 
Execute time 0.0005 milliseconds 
0: //php.net/manual/en/function.preg-match.php 
1: /manual/en/function.preg-match 

|/[^ /] + (. *) \.|

  • encuentran literal '/' seguido por al menos 1 o más no literal '/'
  • agresiva seleccionar todo antes del último literal ''
 
    re> |/[^/]+(.*)\.| 
Compile time 0.0008 milliseconds 
Memory allocation (code space): 23 
    Study time 0.0002 milliseconds 
Capturing subpattern count = 1 
No options 
First char = '/' 
Need char = '.' 
Subject length lower bound = 3 
No set of starting bytes 
data> http://php.net/manual/en/function.preg-match.php 
Execute time 0.0005 milliseconds 
0: /php.net/manual/en/function.preg-match. 
1: /manual/en/function.preg-match 

|/[^ /] + \ K * (= \?.). |

  • encuentran literal '/' seguido por al menos 1 o más no literal '/'
  • Restablecer Seleccione Inicio \ K
  • agresiva seleccionar todo antes
  • mirar hacia adelante última literal ''
 
    re> |/[^/]+\K.*(?=\.)| 
Compile time 0.0009 milliseconds 
Memory allocation (code space): 22 
    Study time 0.0002 milliseconds 
Capturing subpattern count = 0 
No options 
First char = '/' 
No need char 
Subject length lower bound = 2 
No set of starting bytes 
data> http://php.net/manual/en/function.preg-match.php 
Execute time 0.0005 milliseconds 
0: /manual/en/function.preg-match 

| \ w + \ K /.* (= \?.) |

  • encontrar uno o varios Palabra (\ w) caracteres antes de un literal '/'
  • reinicio seleccione Inicio \ K
  • seleccione literal '/' seguido por
  • nada antes
  • mirar hacia adelante último literal '.'
 
    re> |\w+\K/.*(?=\.)| 
Compile time 0.0009 milliseconds 
Memory allocation (code space): 22 
    Study time 0.0003 milliseconds 
Capturing subpattern count = 0 
No options 
No first char 
Need char = '/' 
Subject length lower bound = 2 
Starting byte set: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P 
    Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z 
data> http://php.net/manual/en/function.preg-match.php 
Execute time 0.0011 milliseconds 
0: /manual/en/function.preg-match 
-1

http:[\/]{2}.+?[.][^\/]+(.+)[.].+

vamos a ver, lo que trae:

http:[\/]{2}.+?[.][^\/] - grupo sin captura para http://php.net

(.+)[.] - parte de captura hasta último punto se producen: /manual/en/function.preg-match

[.].+ - extensión correspondiente de un archivo como este: .php

Cuestiones relacionadas