jsherk
jsherk

Reputation: 6472

Replace specific parts of string in PHP

I have a string that looks like this:

$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';

I need to replace the text between the quotes for both title= and desc=

The order of the title and desc can change, meaning desc could be before title, or there could be other things like aaa= or bbb= before/inbetween/after as well.

I can not use str_replace because I do not know what text will appear in the between the quotes.

I am thinking that one possible solution is that I could explode on title= and then explode on double-quote and then piece it back together with new text, and repeat for desc=

Just wondering if there is a better solution that I am not aware of for doing something like this?

Upvotes: 2

Views: 84

Answers (2)

Pavel Musil
Pavel Musil

Reputation: 494

Use regexp php function preg_replace, you may add search patterns and replacement pass as two arrays:

$string = preg_replace([
      '/ title="[^"]+"/',
      '/ desc="[^"]+"/',
   ], [
      sprintf(' title="%s"', 'replacement'),
      sprintf(' desc="%s"', 'replacement'),
   ], $string);

    // NOTE: Space was added in front of title= and desc= 
    // EXAMPLE: If you do not have a space, then it will replace the text in the quotes for title="text-will-get-replaced" as well as something similar like enable_title="text-will-get-replaced-as-well". Adding the space will only match title= but not enable_title=

Upvotes: 4

jsherk
jsherk

Reputation: 6472

Just for interest and comparison sake, I am posting my original function as an example of "how not to do it".

I recommend Pavel Musil's answer using preg_replace instead of this:

<?php

$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';

$new_string = replaceSpecial('title=', '"', 'my new text', $string);

echo $new_string; // will output: [some_block title="my new text" aaa="something" desc="anytext" bbb="something else"]

function replaceSpecial($needle, $text_wrapper, $new_text, $haystack) {
    $new_string = $haystack;
    $needle_arr = explode($needle, $haystack, 2);
    if (count($needle_arr) > 1) {
        $wrapper_arr = explode($text_wrapper, $needle_arr[1], 3);
        $needle_arr[1] = $wrapper_arr[0].$needle.'"'.$new_text.'"'.$wrapper_arr[2];
        $new_string = $needle_arr[0].$needle_arr[1];
    }
return $new_string;
}

?>

Upvotes: 0

Related Questions