Reputation: 63
How to remove all the special character In start(First Letter Should Be Alphanumeric) of a string using PHP ? Please
$String = "+&,Hello+{+ +$world";
After remove all special character in start of a string
The string should become "Hello+{+ +$world"
Help me.
Upvotes: 0
Views: 4517
Reputation: 117
<?php
function string_cleaner($result)
{
$result = strip_tags($result);
$result = preg_replace('/[^\da-z]/i', ' ', $result);
$result = preg_replace('/&.+?;/', '', $result);
$result = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', ' ', $result);
$result = preg_replace('|-+|', ' ', $result);
$result = preg_replace('/_+/', ' ', $result);
$result = preg_replace('/&#?[a-z0-9]+;/i','',$result);
$result = preg_replace('/[^%A-Za-z0-9 _-]/', ' ', $result);
$result = preg_replace('/^\W+|\W+$/', '', $result);
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result, ' ');
return $result;
}
?>
<?php
echo string_cleaner($content);
?>
Upvotes: 1
Reputation: 7706
This will replace everything in the beginning which is not alphanumeric:
preg_replace('/^([^a-zA-Z0-9])*/', '', $string);
UPDATE:
If you need to trim non-alphanumeric characters both in the start and in the end of a string use this:
<?php
$string = "++&5Hello ++f s world6f++&ht6__) ";
echo preg_replace('/(^([^a-zA-Z0-9])*|([^a-zA-Z0-9])*$)/', '', $string);
Upvotes: 2
Reputation: 3149
try to use trim
for more information see this http://php.net/manual/en/function.trim.php
for remove from start of string you can use ltrim
http://www.php.net/manual/en/function.ltrim.php
for remove from end of string you can use rtrim
http://www.php.net/manual/en/function.rtrim.php
code for Your sample
$String = "+&,Hello+{+ +$world";
echo ltrim($String,"&+,");
you can add more character in ltrim for remove from first of string
Upvotes: 2
Reputation: 4550
I think using ltrim will be more useful as you want to remove in starting of the string : http://www.php.net/manual/en/function.ltrim.php
Upvotes: 0
Reputation:
Use trim - it's an in-built function: http://php.net/manual/en/function.trim.php
Upvotes: 0
Reputation: 1617
try this
preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
Upvotes: 0