我需要检查传入的字符串,只留下匹配的字符:
只有一个点(第一个)
$string = 'contDADdas7.6.asdASDj_@@e1!Ddd__aa#S.txt';
$pattern = "/[a-z_0-9]+/";
preg_match_all("/[a-z_0-9]+/", $name, $result);
echo implode('', $result[0]);
必须是
contdas7.6asdj_e1dd__aatxt
它匹配前三个点,我怎么才能只拿一个第一个点?
答案 0 :(得分:4)
你可以试试这个:
$string = strrev($string);
$string = preg_replace('~[^a-z0-9_.]++|\.(?![^.]*$)~', '', $string);
$string = strrev($string);
另一种方式:
$strs = explode('.', $string);
if (count($strs)>1) {
$strs[0] .= '.' . $strs[1];
unset($strs[1]);
}
$string = preg_replace('~[^a-z0-9_.]++~', '', implode('', $strs));
答案 1 :(得分:0)
<?php
$str = "contDADdas7.6.asdASDj_@@e1!Ddd__aa#S.txt";
preg_match_all("/[a-z_0-9\.]+/", $str, $match);
$newstr = implode("", $match[0]);
echo substr_replace(str_replace(".", "", $newstr), ".", strpos($newstr, "."), 0);
<强>输出强>:
contdas7.6asdj_e1dd__aatxt