在PHP

时间:2017-01-10 20:18:57

标签: php regex preg-replace

如何将URL转换为另一个使用PHP 为例

domain.com to domain2.com

domain.com/content to cdn.domain2.com

1 个答案:

答案 0 :(得分:0)

<强> 1。将“domain.com”转换为“domain2.com”

<?php 
$re = '/(?=\.)/m';
$str = 'domain.com
';
$subst = '2'; //add text

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;
?>

<强> 1。结果

domain2.com

<强> 2。将“domain.com/content”转换为“cdn.domain2.com”

<强> REGEXP:
1

/(?=\.)/m

<强> 2

/\/.*/m

第3

/^(?=\w)/m

<强> 2。代码PHP:

<?php 
$re = '/(?=\.)/m';
$str = 'domain.com/content';
$subst = '2';

$result = preg_replace($re, $subst, $str); //domain2.com/content

$re = '/\/.*/m';
$str = $result; //domain2.com
$subst = '';

$result = preg_replace($re, $subst, $str);

$re = '/^(?=\w)/m';
$str = 'domain2.com';
$subst = 'cdn.';

$result = preg_replace($re, $subst, $str); //cdn.domain2.com

echo $result;
?>

<强>结果:

cdn.domain2.com

<强>享受