...

View Full Version : Regular Expression



xiaodao
03-20-2009, 12:14 PM
Hi

String: Conan DJ ~ I'm Not A Kid
String: History's Strongest Disciple Kenichi

Basically i want to make a regular expression to extract only "ALPHABET" string from the above strings and replace space with _, no numbers, no symbols. Anybody can give a solution?


Regards
XD

wb4php
03-20-2009, 03:46 PM
String: Conan DJ ~ I'm Not A Kid
String: History's Strongest Disciple Kenichi



$str1 = "Conan DJ ~ I'm Not A Kid";
$str2 = "History's Strongest no. 1 Disciple Kenichi the 2nd";

/* Each separate space replaced with _: */
$str1 = preg_replace("/[^a-zA-Z ]/", "", $str1); /* Keeps only a-z, A-Z and space */
$str1 = preg_replace("/[ ]/", "_", $str1);
echo $str1."\r\n";

/* => Conan_DJ__Im_Not_A_Kid */

/* 1 or more consecutive spaces replaced with _: */
$str1 = preg_replace("/[^a-zA-Z ]/", "", $str1); /* Keeps only a-z, A-Z and space */
$str1 = preg_replace("/[ ]+/", "_", $str1);
echo $str1."\r\n";

/* => Conan_DJ_Im_Not_A_Kid */

/* All-in-one replacement expression */
echo $str2." => ";
$str2 = preg_replace("/[ ]+/", "_", preg_replace("/[^a-zA-Z ]/", "", $str2));
echo $str2."\r\n";

/* => Historys_no_Strongest_Disciple_Kenichi_the_nd */


There are probably more artful ways to do this. :D

wb4php



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum