-7

My question is the following: I need to set curly brackets in the first two characters in a string

$string = "We want home";

echo $string;

I want to echo this:

(We) Want home

Thanks in advance.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
Gengaver
  • 5
  • 4

2 Answers2

1
        $s='We want to go home';
        echo preg_replace('@^(\w{2})@','($1)',$s );
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

One solution:

<?php
$string = "We want home";
$parts = explode(' ', $string);
$parts[0] = '('.$parts[0].')';
$string = implode($parts, ' ');
var_dump($string); // outputs "(We) want home"

You could as well use regex.

D4V1D
  • 5,805
  • 3
  • 30
  • 65