2

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!

Shoe
  • 74,840
  • 36
  • 166
  • 272
NewPHP
  • 608
  • 2
  • 15
  • 28

6 Answers6

2

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.

Zalaboza
  • 8,899
  • 16
  • 77
  • 142
1

You could use preg_replace and specify the end of string marker $:

$string = preg_replace("/" . $domainNAME . "$/", " ", $string);
James
  • 20,957
  • 5
  • 26
  • 41
1
$domainNAME="example.com";
$result="_xmpp-client._tcp.example.com..example.com";
$string = $result;
$string = substr($result,0, strrpos($result, $domainNAME)-1);   
echo $string;
Rajeesh V
  • 402
  • 5
  • 19
1

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);

Demo

Class
  • 3,149
  • 3
  • 22
  • 31
0
            $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

fembb
  • 44
  • 1
  • 5
0

Use str_ireplace('example.com.example.com', 'example.com', $string);