$re = '/(?(DEFINE) # Definitions
(?<needle>\\\\dfrac(?=[^\}]*\})) # What to search for
(?<skip>^[^\{]*\{|\}[^\{]*\{) # What we should skip
)
(?&skip)(*SKIP)(*FAIL) # Skip it
|
(?&needle) # Match it/mx';
$str = 'Démontrer par récurrence que pour tout entier naturel n,
\\dfrac
\\(\\displaystyle{1^2+2^2+\\ldots+n^2=\\sum_{k=0\\dfrac dsdq ds}rr^{n}k^2=\\dfrac{n(n+1)(2n+1)}{6}}\\)
Démontrer par récurrence que pour tout entier naturel n,
\\(\\displaystyle{1^2+2^2+\\ldots+n^2=\\sum_{k=0\\dfrac{test} fdfd}^{n}k^2=\\dfrac{n(n+1)(2n+1)}{6}}\\)
\\dfrac';
$subst = "\\frac";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php