Reputation: 229
I'm using a variable called $contact_location a few times.
It works fine up until I need to use it for a URL.
Example string:
"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
Is there a way to format a variable only if it comes after something like ".com/"
The url should read www.ourwebsite.com/new-mexico
I know how to str_replace
str_replace(" ","-",$contact_location);
Upvotes: 1
Views: 70
Reputation: 1415
Try this:
<?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);
By using preg_match
and preg_replace
, you can easilly perform a replacement in string based on a pattern.
I was assuming then you're looking for a web site content to change, so, my pattern is '/www\..*/'
. But, if you want to change it, to .com
as mentioned on your question, just replace $pattern
value to your desired match.
Here, a simple regex trainning.
Upvotes: 1
Reputation: 153
$text = "Your text will be here www.yourdomain.com";
$contact_location = "new-maxico";
if (stripos($text, ".com") !== false) {
$text = $text . "/" . $contact_location;
}
This will help you for sure
Upvotes: 0