<?php

$string1 = "This is a test XYZ something else";
$string2 = "This is a test? XYZ something else";
$pattern = " XYZ";
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string1) . PHP_EOL;
echo preg_replace_callback('~\B'.$pattern.'~', function($m) { return trim($m[0]); }, $string2);