SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Get my greedy down dotJoon's Avatar
    Join Date
    Apr 2003
    Location
    daejeon, South Korea
    Posts
    2,223
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    replacing the 1st target only

    Code:
    code
    
    $myString="123123123";
    
    $myString =str_replace("2","x",$myString);
    
    result
    
    1x31x31x3
    The code above produces the result above.

    The would-be code below doesn't work correctly, but I hope it shows what I want.
    Code:
    would-be code
    
    $myString =str_replace_1stOnly("2","x",$myString);
    
    target result
    
    1x3123123

  2. #2
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,396
    Mentioned
    61 Post(s)
    Tagged
    0 Thread(s)
    You could instead use preg_replace() which accepts a fourth argument, $limit, that instructs it to only do that many replacements.

    PHP Code:
    $myString preg_replace('/2/''x'$myString1); 
    Salathe
    Software Developer and PHP Manual Author.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •