soavahaf
soavahaf

Reputation: 63

remove all the special character In start of a string using PHP

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

Answers (6)

Devan
Devan

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

Harry Dobrev
Harry Dobrev

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

mohammad mohsenipur
mohammad mohsenipur

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

Devesh
Devesh

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

user2207091
user2207091

Reputation:

Use trim - it's an in-built function: http://php.net/manual/en/function.trim.php

Upvotes: 0

thumber nirmal
thumber nirmal

Reputation: 1617

try this

   preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

Upvotes: 0

Related Questions