在字符串中的字符后格式化变量

时间:2017-09-15 13:01:42

标签: php

我使用了一个名为$ contact_location的变量几次。

它工作正常,直到我需要将它用于URL。

示例字符串:

"Hello, from $contact_location, please visit www.ourwebsite.com/$contact_location"

output: Hello, from New Mexico, please visit www.ourwebsite.com/New Mexico.

Needed Output: Hello, from New Mexico, please visit www.ourwebsite.com/new-mexico

是否有办法格式化变量,只要它出现在" .com /"

之类的东西之后

该网址应为www.ourwebsite.com/new-mexico

我知道如何str_replace

str_replace(" ","-",$contact_location);

2 个答案:

答案 0 :(得分:1)

试试这个:

<?php
function formatUrl($msg)
{    
    $pattern = '/www\..*/';
    preg_match($pattern, $msg, $matches);
    return preg_replace($pattern, strtolower(str_replace(' ','-',$matches[0])),$msg);
}

$contact_location = 'New Mexico';
$msg = formatUrl("Hello, from $contact_location, please visit www.ourwebsite/$contact_location");
var_dump($msg);

通过使用preg_matchpreg_replace,您可以根据模式轻松执行字符串替换。

我假设您正在寻找要更改的网站内容,因此,我的模式为'/www\..*/'。但是,如果您想更改问题,请按照问题中提到的.com进行更改,只需将$pattern值替换为您想要的匹配项。

Here, a simple regex trainning

答案 1 :(得分:0)

$text = "Your text will be here www.yourdomain.com";
$contact_location = "new-maxico";
if (stripos($text, ".com") !== false) {
   $text = $text . "/" . $contact_location;
}

这对您有帮助