Insert a string into a string given an index

13,572

Solution 1

You can do anything with regular expressions!

For your specific request, the solution would be:

$var = 'myimage.jpg';
$new_var = preg_replace('/\.jpg$/', '.big$0', $var);

I would suggest reading up on how to write regular expressions, as they can be very useful in development (here's a starting point).

Solution 2

You can use substr_replace to insert a string by replacing a zero-length substring with your insertion:

$string = "some-image.jpg";
$insertion = ".big";
$index = 10;

$result = substr_replace($string, $insertion, $index, 0);

From the manual page (the description of the length (4th) argument):

If length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Solution 3

See this: http://www.krizka.net/2007/12/29/how-to-insert-a-string-into-another-string-in-php/

$newstring=substr_replace($orig_string, $insert_string, $position, 0);
Share:
13,572
Derek Adair
Author by

Derek Adair

Building all the things

Updated on June 16, 2022

Comments

  • Derek Adair
    Derek Adair almost 2 years

    I know this is a really simple question, but I was just wondering if there is a native php method to inject a string into another string. My usual response to a new text manipulation is to consult the manual's listings of string functions. But I didn't see any native methods for explicitly inserting a string into another string so I figured i'd consult SO.

    The answer is likely some kind of combination of the php native string functions OR simply regex (which makes my eye's bleed and my brain melt so I avoid it).

    EX: Take a string like some-image.jpg and inject .big before .jpg yielding some-image.big.jpg

  • Derek Adair
    Derek Adair over 13 years
    lol refer to my eye's bleeding comment. I'm not opposed to using regex, just writing it!!! haha. Although I've come to terms with the fact that I need to buck up and learn it better.
  • Derek Adair
    Derek Adair over 13 years
    my eye's hatred for regex aside... this is a superb tutorial on regex - phpfreaks.com/tutorial/regular-expressions-part1---basic-syn‌​tax
  • Bruce
    Bruce over 13 years
    @Derek regular-expressions.info/tutorial.html if you want to learn regex better ;)
  • Andy
    Andy over 11 years
    Much better answer IMO. Using a regex for something as simple as this is overkill
  • CptAJ
    CptAJ almost 11 years
    This assumes that we know the index. We probably don't... so yeah, regex
  • Bruce
    Bruce almost 11 years
    The question stated given an index. :)