- preg_replace_callback: documentation ( source)
- strtolower: documentation ( source)
<?php
$expression = "/(?J)\b(?:
(?<obj>i)(?:(?<part>'m)|\s(?<part>am|was))?
|(?<obj>you|they)(?:(?<part>'re)|\s(?<part>are|were))?
|(?<obj>it|he|she)(?:(?<part>'s)|\s(?<part>is|was))?
|(?<obj>(my|your|it)sel(f|ves))
)\b/uix";
$message = "that you are not who you think you're but I'm not myself either";
echo $output = preg_replace_callback($expression,
function ($matches){
$o = '';
$object = strtolower($matches['obj']);
switch($object){
case 'i':
$o = 'you';
break;
case 'you':
$o = 'I';
break;
case 'yourself':
$o = 'myself';
break;
case 'myself':
$o = 'yourself';
break;
default:
$o = $object;
}
if(isset($matches['part'])){
switch($part = strtolower($matches['part'])){
case "'re":
case "are":
if($object == 'you')
$o .= ' am';
break;
case 'am':
$o .= ' are';
break;
case "'m":
$o .= "'re";
break;
case 'was':
if(!in_array($object, ['he','she','it']))
$o .= ' were';
break;
case 'were':
if($object == 'you')
$o .= ' was';
break;
}
}
return $o;
}, $message
);