4

i want a php function probably regular expression to find and replace a string that starts with a constant string and ends up with a specific string and the text mentioned within those strings.. e.g.,

[Starting String]..anything.. [Ending String]

and i want to remove above pattern of string with empty space.. Kindly advise!!

2
  • Give an example, please. Commented Feb 22, 2012 at 5:40
  • 1
    Please, explain better what do you want. Commented Feb 22, 2012 at 5:45

3 Answers 3

15
$str = preg_replace('/' . preg_quote('[Starting String]') . 
                          '.*?' .
                          preg_quote('[Ending String]') . '/', '', $str);

preg_quote is used to be sure that you will not break the regexp with some specific for regexp characters in your 'Starting' and 'Ending' strings, like []

For $str = ' blah blah [Starting String] something [Ending String] blah blah'; the result would be blah blah blah blah

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

2 Comments

How can i replace by condition. Ex. if text is a then replace by b, if text is c then replace by d.
@dungphanxuan use preg_replace_callback
1

I believe you want to use preg_replace. I haven't tested it, but something along the lines of:

$str = "Starting String foo bar Ending String"
$pattern = '/^Starting String(.+)Ending String$/'
$replacement = ''
$result = preg_replace($pattern, $replacement, $str);

You will have to make sure that Starting String and Ending String do not contain any special regex characters or that they are properly escaped.

1 Comment

I think Cheery's answer is probably a little more correct than mine
1
define('STARTING', 'starting string');

$ending = 'ending string';
$string = 'starting stringSomething Hereending string';

function get_anything($string, $ending, &$anything)
{
    if (strpos($string, STARTING) !== 0)
    {
        return false;
    }
    if (substr($string, strlen($ending) * -1) != $ending)
    {
        return false;
    }
    $anything = substr($string, strlen(STARTING));
    $anything = substr_replace($anything, '', strlen($ending) * -1, -1);
    return true;
}

if (get_anything($string, $ending, $anything))
{
    echo $anything;
}

The function get_anything will return false if the pattern is not found, and true if it is found. The "anything" in the middle will be returned in the third parameter.

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.