Uso avanzado de expresiones regulares en PHP

Interesante y completo tutorial en el que se nos explica usos de las expresiones regulares que normalmente no solemos tener en cuenta:

Añadir comentarios

preg_match("/^
    (1[-\s.])?	# optional '1-', '1.' or '1'
    ( \( )?		# optional opening parenthesis
    \d{3}		# the area code
    (?(2) \) )	# if there was opening parenthesis, close it
    [-\s.]?		# followed by '-' or '.' or space
    \d{3}		# first 3 digits
    [-\s.]?		# followed by '-' or '.' or space
    \d{4}		# last 4 digits
  $/x",$number);

Callbacks

$template = preg_replace_callback('/\[(.*)\]/','my_callback',$template);  
function my_callback($matches) {  
  /* codigo */
}

‘Codicia’ de la regexp

$html = 'Hello World!';  
// note the ?'s after the *'s  
if (preg_match_all('/.*?<\/a>/',$html,$matches)) {  
  print_r($matches);  
}

Prefijos y sufijos

$pattern = '/foo(?=bar)/'; 
$pattern = '/foo(?!bar)/'; 
$pattern = '/(?

Condicionales

// if it begins with 'q', it must begin with 'qu'  
// else it must begin with 'f'  
$pattern = '/^(?(?=q)qu|f)/';

Subpatrones

preg_match('/(?PH.*) (?Pf.*)(?Pb.*)/', 'Hello foobar', $matches);  
echo "f* => " . $matches['fstar']; // prints 'f* => foo'  
echo "b* => " . $matches['bstar']; // prints 'b* => bar' 

Advanced Regular Expression Tips and Techniques

Similar Posts

2 Comments

Comments are closed.