Uso avanzado de expresiones regulares en PHP   
Author: admin

Abril 21, 2010

Posted in artículos | |

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 = '<a href="/hello">Hello</a> <a href="/world">World!</a>';
// note the ?'s after the *'s
if (preg_match_all('/<a.*?>.*?<\/a>/',$html,$matches)) {
  print_r($matches);
}

Prefijos y sufijos

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

Condicionales

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

Subpatrones

preg_match('/(?P<hi>H.*) (?P<fstar>f.*)(?P<bstar>b.*)/', 'Hello foobar', $matches);
echo "f* => " . $matches['fstar']; // prints 'f* => foo'
echo "b* => " . $matches['bstar']; // prints 'b* => bar'

Advanced Regular Expression Tips and Techniques

Nuestra fuente: Sentidoweb

Leave a Reply