删除字符串开头和结尾的空格
问题描述:
我对于正则表达式很新颖。 我需要清理从开始和结束的空格搜索字符串。 例:“搜索字符串” 结果:“搜索字符串”删除字符串开头和结尾的空格
我有工作作为一个JavaScript的解决方案的模式,但我不能得到它使用的preg_replace PHP的工作:
的Javascript百通的作品:
/^[\s]*(.*?)[\s]*$/ig
我的例子:
$string = preg_replace('/^[\s]*(.*?)[\s]*$/si', '', " search string ");
print $string; //returns nothing
在解析它告诉我,G不承认,所以我不得不祛瘀然后将ig更改为si。
答
是的,你应该使用TRIM()我想..但如果你真的想要的正则表达式,那就是:
((?=^)(\s*))|((\s*)(?>$))
+1
谢谢这个解决方案工作以及:preg_replace('/ ^((?= ^)(\ s *))|((\ s *)(?> $))/ si','',“asd asd”); – Alex
的可能重复[使用预浸\ _replace在字符串末尾删除多余的空间](http://stackoverflow.com/questions/4787219/remove-extra-space-at-the-end-of-string-using-preg-replace) –
这是一个稍微不同于http:// stackoverflow的问题。 com/questions/4787219/remove-extra-space-at-the-end-of-string-using-preg-replace,它询问如何仅删除字符串末尾的空格,其中我的问题用于开始和结束。这个解决方案不同于@daron – Alex