Page 1 of 1
can any one help me in string padding.
Posted: Mon Dec 05, 2005 1:05 am
by itsmani1
I need help in string padding....
my input is :
Code: Select all
$input = "Alien Is my friend, and I like mango.";
now i want to padd all i's and I's with "_" on both sides.
means i want output like this:
Code: Select all
$outut = "Al_i_en _I_s my fr_i_end, and _I_ l_i_ke mango.";
Posted: Mon Dec 05, 2005 1:38 am
by itsmani1
Code: Select all
if (preg_match ("/php/i", "PHP is the web scripting language and php is my 1st choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
in the above example i can check the string now how can i padd "_" on both sides of all "php"'s
Posted: Mon Dec 05, 2005 2:00 am
by shiznatix
OR! you can just do this
Code: Select all
$string= "Alien Is my friend, and I like mango.";
$string = str_replace('i', '_i_', $string);
$string = str_replace('I', '_I_', $string);
echo $string;
Posted: Mon Dec 05, 2005 2:34 am
by m3mn0n
You can find many more interesting functions to work with strings at the PHP Manual
Strings page.
Posted: Mon Dec 05, 2005 3:25 am
by itsmani1
shiznatix wrote:OR! you can just do this
Code: Select all
$string= "Alien Is my friend, and I like mango.";
$string = str_replace('i', '_i_', $string);
$string = str_replace('I', '_I_', $string);
echo $string;
is there any better solution than the above one using reguller expression.....
thanx.
Posted: Mon Dec 05, 2005 3:52 am
by onion2k
itsmani1 wrote:shiznatix wrote:OR! you can just do this
Code: Select all
$string= "Alien Is my friend, and I like mango.";
$string = str_replace('i', '_i_', $string);
$string = str_replace('I', '_I_', $string);
echo $string;
is there any better solution than the above one using reguller expression.....
thanx.
For a simple replacement like that it's actually faster (by quite a lot) to use a couple of str_replace()s than one regular expression.
Posted: Mon Dec 05, 2005 3:54 am
by Chris Corbyn
Code: Select all
function padd_at_string($input, $str)
{
$escaped = preg_quote($str);
$re = '/('.$escaped.')/';
return preg_replace($re, '_$1_', $input);
}
EDITTED 3 times

Too early

Posted: Mon Dec 05, 2005 4:03 am
by itsmani1
d11wtq wrote:Code: Select all
function padd_at_string($input, $str)
{
$escaped = preg_quote($str);
$re = '/('.$escaped.')/';
return preg_replace($re, '_$1_', $input);
}
EDITTED 3 times

Too early

thanx. man for your time but can you do me one more favour. this don't work with case in-sensitive. can u solve this .
Posted: Mon Dec 05, 2005 4:14 am
by onion2k
itsmani1 wrote:thanx. man for your time but can you do me one more favour. this don't work with case in-sensitive. can u solve this .
Your signature: "Home Page Of AM Solutions :: We Solve Problems".

Posted: Mon Dec 05, 2005 5:44 am
by Chris Corbyn
Code: Select all
function padd_at_string($input, $str)
{
$escaped = preg_quote($str);
$re = '/('.$escaped.')/i';
return preg_replace($re, '_$1_', $input);
}