Search code examples
phpexplodesubstr

php string manipulation issues


I have the following string...

$string = "True is True (5-7 years)";

what I want is to get - TiT(5-7 years)

I have tried the following code but no luck...

$string = "True is True (5-7 years)"; 
$explodedString = explode(" ",$string); 
for($i = 0; $i < 4; $i++){ 
    $tempString = substr($explodedString[$i], 0, 1); 
    $finalString .= $tempString; 
}  

In short, I need the first three words of its initials and the remaining in bracket is as it is like this.... TiT(5-7 years). how?


Solution

  • This a good case for using regular expressions:

    $str = 'True is True (5-7 years)';
    preg_match_all('~\([^()]*\)|\b\w~', $str, $matches);
    echo implode("", $matches[0]); // TiT(5-7 years)
    

    Regex breakdown:

    • \([^()]*\) Match anything inside parentheses including themselves
    • | Or
    • \b\w Match first word character from a word