How can I remove all non alpha numeric characters and leading zeros

谁说胖子不能爱 提交于 2019-12-12 04:55:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!