开发者

Php question on regular expressions [duplicate]

开发者 https://www.devze.com 2023-04-03 17:09 出处:网络
This question already has answers here: Remove everything except letters from PHP string (3 answers) 开发者_开发知识库
This question already has answers here: Remove everything except letters from PHP string (3 answers) 开发者_开发知识库 Closed 9 years ago.

i have a string say "hey how are you going Mr. Matt" now i want to be able replace all characters in this string including double quotes that aren't [a-z][A-Z] letters how do i achieve it in php?


http://php.net/manual/en/function.preg-replace.php

<?php
    $string = '"hey how are you going Mr. Matt"';
    $pattern = '/[^a-zA-Z]/';
    $replacement = '-';
    echo preg_replace($pattern, $replacement, $string);
?>

Live example (codepad).

/[^a-zA-Z]/ is the regular expression. It is basically just a set ([ ]) containing a-z and A-Z. It is however inverted (^), so it matches all non-alphabetic characters, and replaces them.


$clean_string = preg_replace('/[^a-zA-Z]/','',$string); 

Will replace everything that's not a-zA-Z. Add a space in the [] if you need them, or a /s if you want all whitespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消