0

I have some strings which contain the words LIMIT 3, 199 or LIMIT 0, 100.

Basically I want to replace the word LIMIT and everything after it in my string.

How do I do this in PHP? str_replace only replaces an item and the LIMIT text after is dynamic/

So it could be

WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121
// RETURN WOULD BE
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT

WHEN JOHN TRIED LIMIT 343, 333 HE FOUND
// RETURN WOULD BE
WHEN JOHN TRIED 

5 Answers 5

3

Use strpos to find the position of LIMIT within the string, and then use substr to return the string up until that point. Really pretty basic string manipulation.

Or perhaps use preg_replace if you want a one-liner, though I don't think going to the regex toolchest is needed here.

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

3 Comments

That's still a one liner :) substr($string,0,strpos($string,"LIMIT"));
But that only works if he has LIMIT etc. in his string once.
@Asad that is correct, but the requirement was to remove everything after an occurrence of LIMIT, so if it is in there two or more times, the multiple occurrences would be removed when removing everything after the first occurrence.
2

Replace out LIMIT.+$ using preg_replace with pattern /LIMIT.+$/m

That is to say:

$string = preg_replace("/LIMIT.+$/m","",$string);

1 Comment

Happy with all answers. Thanks
0

Use strstr or stristr (case insensitive). Will work only for versions >= php 5.3.0

$str = strstr($your_string, 'LIMIT', true);

Comments

0

As I recommend against using regexes when you don't understand them, here's a simple answer that doesn't use them (do note, I do recommend learning regexes, but they aren't easy to learn):

$output = substr($input, 0, strpos($input, 'LIMIT'))

1 Comment

This deletes everything BUT the LIMIT etc
0

You can use strstr

$break = "LIMIT";
$array = array();
$array[] = "WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121";
$array[] = "WHEN JOHN TRIED LIMIT 343, 333 HE FOUND";

echo "<pre>";
foreach ( $array as $value ) {
    echo strstr($value, $break, true), PHP_EOL;
}

Output

WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT 
WHEN JOHN TRIED 

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.