0

I have got a string and would like to remove everything after a certain "dot"+word combination. For instance:

This.Is.A.Test

=> would become

This.Is.A
3
  • I have a very similar function working in javascript (split) and I was searching for a similar one in PHP. I think "explode" might be a good way, but I wasnt able to figure it out from the examples here. Commented May 21, 2012 at 13:47
  • Get the position of ".A" using strpos() and use substr() to get the string result. Use PHP manual Commented May 21, 2012 at 13:51
  • Are you trying to remove everything after a specific dot+word or just after the last dot+word? What if the string was "This.Is.A.Test."? Should it just remove the last dot, or does it need to be followed by a word? Commented May 21, 2012 at 14:04

5 Answers 5

3

Were you looking to remove everything after a specific dot+word, or just remove the last dot+word? If you're looking for a specific word, try this:

$str = "This.Is.A.Test";
$find = ".A";
$index = strpos($str, $find);
if ($index !== false)
    $str = substr($str, 0, $index + strlen($find));
echo $str; // "This.Is.A"

In response to @SuperSkunk:

If you wanted to match the whole word, you could do this:

$find = ".A.";

$str = "This.Is.A.Test";
$index = strpos($str, $find);
if ($index !== false)
    $str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.A"

$str = "This.Is.AB.Test";
$index = strpos($str, $find);
if ($index !== false)
    $str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.AB.Test" (did not match)
Sign up to request clarification or add additional context in comments.

2 Comments

@SuperSkunk: Depends on if that's what the OP is actually looking for. See updated answer.
Just realized that you would get weird results if $find wasn't actually found in the string (meaning strpos would return false). Updated answer.
1

$str = "This.Is.A.Test"; $str = substr($str, 0, strrpos($str, "."));

1 Comment

This was the first answer I have tried and it worked just fine!
0
$result = explode('.', $str, 4);
array_pop($result);
implode('.', $result);

Comments

0

I'll do something very simple like :

<?php

$string = 'This.Is.A.Test';

$parts = explode('.', $string);
array_pop($parts); // remove last part
$string = implode('.', $parts);

echo $string;

?>

Comments

0

$pos = strpos($haystack, ".A" );

$result = substr($haystack,0,$pos);

...something like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.