This question already has an answer here:
I need to remove the domain name from the end of a string. I have tried the following code:
$domainNAME="example.com";
$result="_xmpp-client._tcp.example.com..example.com"
$string = $result;
$string = str_replace(".".$domainNAME, " ", $string);
Here the result is "_xmpp-client._tcp.". But the result should be "_xmpp-client._tcp.example.com.".
I need to remove the domain name only from the end of string, if domain name exists anywhere in the string it should not be removed.How can I change the code for that?
Any help should be appreciated!
</div>
You could use preg_replace and specify the end of string marker $
:
$string = preg_replace("/" . $domainNAME . "$/", " ", $string);
No need for fancy preg nor substr.. just use trim() function :)
will remove from both ends
echo trim($string,$domainNAME);
will remove domainName from end of string
echo rtrim($string,$domainNAME);
will remove domainName from beging of string
echo ltrim($string,$domainNAME);
Example
echo rtrim('demo.test.example.com',"example.com");
//@return demo.test
2nd method
if not.. then use the preg match :).
$new_str = preg_replace("/{$domainNAME}$/", '', $str);
this will replace $domainNAME from $str ONLY if its at end of $str ($ sign after the var means AT end of string.
$domainNAME="example.com";
$length = strlen(".".$domainNAME);
$result="_xmpp-client._tcp.example.com..example.com";
$string = substr($result, 0, $length*(-1));
Try that. I wish it could help you
Use str_ireplace('example.com.example.com', 'example.com', $string);
$domainNAME="example.com";
$result="_xmpp-client._tcp.example.com..example.com";
$string = $result;
$string = substr($result,0, strrpos($result, $domainNAME)-1);
echo $string;
if you are truly wanting to have the output as _xmpp-client._tcp.example.com.
with the dot at the end use
preg_replace("/\." . $domainNAME . "$/", " ", $string);
and you can add ? if you want it to be optional
preg_replace("/\.?" . $domainNAME . "$/", " ", $string);