将字符串中的各种空格,统一替换成单一空格
$str = preg_replace('/\s+/', ' ', $str);
对11位数的手机号码用-分割显示
$contact_phone = preg_replace("/^(\d{3})(\d{4})(\d{4})$/","$1-$2-$3",$contact_phone);
获取文本中所有超链接
preg_match_all("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/",$str,$matches)
取http链接正则
http[\w:\/\.\?=&%_]+
匹配文本中所有超链接 只要包括在a标签中的就都筛选出来
/<a[^>]*href=['"]([^"]*)['"].*?[^>]*>(.*?)<\/a>/g
JS演示
var data = str.match(/<a[^>]*href=['"]([^"]*)['"].*?[^>]*>(.*?)<\/a>/g);
将字符串中把图片和其他文本分割出来, 将内容区分成 img 和 非img两类
/((?!<img).)+|<img.*?>/gim
JS演示
var list = content.match(/((?!<img).)+|<img.*?>/gim)
JS正则表达式替换掉指定文本
var regExp = new RegExp('你要替换的文本', 'gi');
newstr = str.content.replace(regExp,''); //目前替换为空串
正则表达式替换掉HTML的标记 只保留文本 如果是PHP 直接调用 strip_tags() ,使用该函数也可以保留部分字符
onlystr = html.replace(/<[^>]+>/g,"")
js 去除空格
/*
去除字符串空格 默认去除前后字符串
当 is_all 为true时 去除文本中所有字符串
*/
function trim(str, is_all = false) {
var result;
result = str.replace(/(^\s+)|(\s+$)/g, "");
if (is_all) {
result = result.replace(/\s/g, "");
}
return result;
}
php去除空格
$html=preg_replace("/[\t\n\r]+/","",$html);
过滤JS脚本、css样式标记
$html = preg_replace("/<script(.*?)<\/script>/is", "", $html);
$html = preg_replace("/<iframe(.*?)<\/iframe>/is", "", $html);
$html = preg_replace("/<style(.*?)<\/style>/is", "", $html);
$html = preg_replace("/{(.*?)}/is", "", $html);
获取html标记里的文本内容
preg_match_all("/<([a-zA-Z0-9:_\-]+).*?>([.\s\S]+?)<\/.+?>/",$html,$data);
文本中 只允许汉字 数字 下划线 字母
if (!preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u", $username)) {
exit("抱歉,用户名只能为汉字、数字、下划线和字母组成!".$username);
}
将匹配到的部分关键字用正则表达式过滤 包括中文和普通字符
$str = preg_replace('/刷([\x{4e00}-\x{9fa5}]{1}|.{1})/iu', '**', $str);
将关键字中间的字符 可以同时包含 中文和英文 替换为指定字符
/脏[\x{4e00}-\x{9fa5}\w]{0,8}话/iu