2015-03-31 52 views
-7

我的问题设置大括号中的前两个字符如下: 我需要设置大括号中的前两个字符串中的字符PHP:字符串

$string = "We want home"; 

echo $string; 

我想呼应这样的:

(We) Want home 

在此先感谢。

+4

你尝试过什么吗? (尝试['substr()'](http://php.net/manual/en/function.substr.php)'echo“(”。substr($ string,0,2)。“)”。substr ($ string,2);') – Rizier123 2015-03-31 09:47:57

+1

只要把它们放在字符串中! – GordonM 2015-03-31 09:51:32

回答

1
 $s='We want to go home'; 
     echo preg_replace('@^(\w{2})@','($1)',$s); 
0

一个解决方案:

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

你还可使用regex