3

I know that to replace spaces I can use:

str_replace(' ', ';', $string);

My question is...how do I replace only the first space?

eg: firstword secondword thirdword to firstword;secondword thirdword

Passerby
  • 9,715
  • 2
  • 33
  • 50
Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • 1
    This might be what you need: http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match – Dean Barnes Apr 04 '14 at 10:52

4 Answers4

8
preg_replace('/ /', ';', $string, 1)
dikesh
  • 2,977
  • 2
  • 16
  • 26
6

I would use preg_replace

$subject='firstword secondword thirdword';
$result = preg_replace('%^([^ ]+?)( )(.*)$%', '\1;\3', $subject);
var_dump($result);
edmondscommerce
  • 2,001
  • 12
  • 21
1

provide replacement count:

str_replace(' ', ';', $string,1);

refer wiki

Elixir Techne
  • 1,848
  • 15
  • 20
  • Getting: Fatal error: Only variables can be passed by reference – Satch3000 Apr 04 '14 at 10:59
  • This is actually invalid. – Barry Aug 07 '18 at 14:22
  • You're using the 4th parameter wrong. You pass a variable to the 4th parameter and it sets that variable to the number of replacements done. It does not determine how many instances are replaces. For that you want to use preg_replace. – Gavin May 19 '22 at 10:22
0

You could use regular expressions with preg_replace, or use stripos. So you would do this:

<?php
$original = 'firstword secondword thirdword';
$result = 
  substr($original,0,stripos($original,' '))
  .';'
  .substr($original,stripos($original,' ')+1);

  echo $result;

See it running here.

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101