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!

0

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

hmmm echo rtrim($string,$domainNAME); returns _xmpp-client._t here.
updated :).. sorry for that confusion
lol, that's my answer now :P
haha :D didnt see that :D Good job you should be accepted :D !
1

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

$string = preg_replace("/" . $domainNAME . "$/", " ", $string);

Comments

1
$domainNAME="example.com";
$result="_xmpp-client._tcp.example.com..example.com";
$string = $result;
$string = substr($result,0, strrpos($result, $domainNAME)-1);   
echo $string;

Comments

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

Comments

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

1 Comment

too much for a simple task.. preg_replace("/{$domainNAME}$/", '', $str); shall do in that case !
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.