Regular/替换域名:修订间差异
来自康健生活
无编辑摘要 |
无编辑摘要 |
||
| (未显示同一用户的3个中间版本) | |||
| 第1行: | 第1行: | ||
== 取网址 == | |||
方法一: | |||
<syntaxhighlight lang="javascript"> | |||
/(http|https):\/\/([\w.]+\/?)\S*/</syntaxhighlight> | |||
方法二: | |||
<syntaxhighlight lang="javascript"> | |||
/http[s]{0,1}:\/\/([\w.]+\/?)\S*/</syntaxhighlight> | |||
使用 js 提取域名(带协议) | |||
<syntaxhighlight lang="javascript"> | |||
url.replace(/(http[s]{0,1}:\/\/[a-zA-Z0-9.-]+)?.*/i,'$1')</syntaxhighlight> | |||
方法三: | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const str = 'http://s3.qhmsg.com/qs/;mapsapi;m/1001.js'; | |||
const reg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/; | |||
const result= str.replace(reg,"kangkk.com"); | |||
console.log(result); | |||
</syntaxhighlight>|{{consoleout|<pre>'http://kangkk.com/qs/;mapsapi;m/1001.js' | |||
</pre>}}}} | |||
== PHP == | == PHP == | ||
正则提取的url中的域名以及替换域名的方法 preg_match()和preg_replace() | 正则提取的url中的域名以及替换域名的方法 preg_match()和preg_replace() | ||
| 第4行: | 第28行: | ||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
<?php | <?php | ||
$url = 'http://www.baidu.com/index.php'; //网站的url | |||
$url = 'http://www.baidu.com/index.php'; | $reg = '/(http):\/\/([^\/]+)/i'; //正则表达式 | ||
$reg = '/(http):\/\/([^\/]+)/i'; | |||
preg_match($reg, $url,$res); | preg_match($reg, $url,$res); | ||
?></syntaxhighlight> | |||
<blockquote><pre> | |||
$res的结果 | |||
array (size=3) | |||
=> string 'http://www.baidu.com' (length=20) | => string 'http://www.baidu.com' (length=20) | ||
=> string 'http' (length=4) | => string 'http' (length=4) | ||
=> string 'www.baidu.com' (length=13) | => string 'www.baidu.com' (length=13) | ||
</pre></blockquote> | |||
<syntaxhighlight lang="php"> | |||
<?php | |||
$url1 = 'www.jingdong.com'; | $url1 = 'www.jingdong.com'; | ||
| 第30行: | 第56行: | ||
$replacements[0] = $url1; | $replacements[0] = $url1; | ||
echo preg_replace($patterns, $replacements, $url); | echo preg_replace($patterns, $replacements, $url); | ||
?></syntaxhighlight> | ?></syntaxhighlight> | ||
<blockquote><pre> | |||
http://www.jingdong.com/index.php | |||
</pre></blockquote> | |||