搜索并替换子字符串中的字符[关闭]

Example:

"Hello iam a [start] string and iam very happy with [end] beeing a string...";

Now lets say i only want to change something in the substring between [start] and [end]. I know how to find out the str_pos and the lenght to the end but how can i search and replace something that only affects this substring?

What i want to do is: (for example) Replace 'x' with 'y' within str positon 5 and 50

I know that there is substr_replace but thats not exactly what iam looking for.

Any ideas would be great, thanks a lot!

How about something like...

<?php

$string = 'my first word was first then it was the second word';

echo "$string
";
echo str_pos_replace($string, 'word', 'second', 'first', 'second') . "
";

function str_pos_replace($string, $start, $end, $find, $replace)
{
        $pos1=strpos($string, $start);
        $pos2=strpos($string, $end);
        $subject=substr($string, $pos1, ($pos2-$pos1));
        $replaced=str_replace($find, $replace, $subject);
        return str_replace($subject, $replaced, $string);
}

Will print out something like:

my first word was first then it was the second word

my first word was second then it was the second word

here is an example pattern to find the letter 'a' between [start] and [end]

(.*\[start\]|\[end\].*)(*SKIP)(*F)|a  

Demo

if is string

str_repalce(needle, replace, haystack)

if array

json_encode haystack
str_replace needle, replace, haystack)
json_decode haystack

Knowing the str position is noit realy of value to you when if you know what you are looking for you can just replace it with some thing else just remember the rule double quotes to use php vars "$haystack" and single quotes will render exactly as you type '$haystack'

this is by far the easyest way and best way to replace text or values in a string or in a array but please read the documentation of the functions before use so you understand how they work. Json_encode / Decode can be a tricky thing to master but once you understand it you can use it to trasform your arrays to strings and back again reall easy.

You could do it with a callback.

Regex:

"/(?xs)^( . {" . $start_pos . "} ) ( . {" . $end_pos . "} )/"

Inside the callback, run a new regex replacement on group 2 for xyz.
Return Catted original group 1 and and the replaced group 2.

Untested code:

$start_pos = 5;
$end_pos = 50;
$str = preg_replace_callback
(
   "/(?xs)^( . {" . $start_pos . "} ) ( . {" . $end_pos . "} )/",
   function( $matches )
   {
      $orig_grp1 = $matches[1];
      $substr_replaced = preg_replace( '/xyz/', 'XYZ', $matches[2] );
      return $orig_grp1 . $substr_replaced;
   },
   $str
 );

So yeah, I was a bit bored, and this might be an overkill, but it does what you ask:

function replaceBetweenTags($needle, $replacement, $haystack, $keepTags = false, $startTag = "[start]", $endTag = "[end]") {

    $startPattern = preg_quote($startTag);
    $endPattern = preg_quote($endTag);
    $pattern = '/'.$startPattern.'(.+)'.$endPattern.'/m';
    if (!preg_match($pattern, $haystack)) return $haystack;

    return preg_replace_callback($pattern, function($match) use ($startTag, $endTag, $keepTags, $needle, $replacement) {
        $match = str_replace($needle, $replacement, $match[0]);
        if ($keepTags) return $match;
        return str_replace($startTag, "", str_replace($endTag, "", $match));
    }, $haystack);


}

Usage is simple:

echo replaceBetweenTags("happy", "sad", "Hello iam a [start] string and iam very happy with [end] beeing a string..."

// Output: Hello iam a  string and iam very sad with  beeing a string...
// Unless you set $keepTags = true, in which case it'll preserve the tags.

It handles multiple tag pairs too. Things to note:

  1. it's case sensitive
  2. $keepTags = false might leave double spaces. You might want to str_replace those

Hope it helps.

If I understand correctly you want to replace something within a substring while knowing it's position within it's parent string. Using substr() and preg_replace can easily do this:

Code:

$str = 'Hello iam a [start] string and iam very happy with [end] beeing a string...';

$begpos = 12; // begin position of [start]
$endpos = 56; // end position of [end]
$substr = substr($str, $begpos, $endpos-$begpos);
$subtit = preg_replace('/\iam/','I AM', $substr);
$newstr = substr_replace($str,$subtit,$begpos,$endpos-$begpos);

echo $newstr; 

Result:

Hello iam a [start] string and I AM very happy with [end] beeing a string...