问题
I want to remove everything from a string using regular expression except alpha and numeric characters and I need any leading zero removed.
The below works but does not remove leading zeros
$string = '00000000A1234567890-=qwesss €#¢∞§¶¶•ªº– ≠≠rtyuuiop[]\';lkjhgfdsazxcvbnm,./';
$pattern = '/([^\da-z]/i)';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
How can i alter the pattern to remove leading Zeros?
回答1:
This one will work:
<?php
$string = '00000000A1234567890-=qwesss €#¢∞§¶¶•ªº– ≠≠rtyuuiop[]\';lkjhgfdsazxcvb00000nm,./';
$pattern = '#^(0*)|([^\da-z])#i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
EDIT
This pattern can also be simplified to:
$pattern = '#^0+|\W#';
回答2:
This should work to satisfy both requirements:
$string = '00000000A1234567890-=qwesss €#¢∞§¶¶•ªº– ≠≠rtyuuiop[]\';lkjhgfdsazxcvbnm,./';
$pattern = '/^0+|[^\dA-Za-z]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
//=> 1234567890qwesssrtyuuioplkjhgfdsazxcvbnm
回答3:
Try it:
$string = '00000000A1234567890-=qwesss €#¢∞§¶¶•ªº– ≠≠rtyuuiop[]\';lkjhgfdsazxcvbnm,./';
$pattern = '/([\W])/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
And if you also want delete zeros pattern is:
$pattern = '/([\W0])/i';
来源:https://stackoverflow.com/questions/24801900/how-can-i-remove-all-non-alpha-numeric-characters-and-leading-zeros