Preg_replace不使用捕获参数和<

When I add the less than "<" symbol

$str = 'test';
$str = preg_replace('@(.*)@isu', '<$1', $str);
echo $str; // outputs ""

It should output <test, but instead outputs nothing.

It works fine when I don't add the character.

$str = 'test';
$str = preg_replace('@(.*)@isu', '$1', $str);
echo $str; // outputs "test"

I tried escaping it

$str = 'test';
$str = preg_replace('@(.*)@isu', '<\\\\$1', $str);
echo $str; // outputs "<\test"

I was unable to find anything about this in the php manual while google just spits out unrelated SO questions.

I would like to know why this does not work?

PHP 5.4.22

I think you are checking the outputs from the browser. That's why its doing such behaviour. From the console it works perfectly. So, I believe you'll find everything when you view the source of html from browser.

Also, you can replace the < with &lt;

Unclear on how <\\\\$1 would escape the less than (<) symbol? Have you tried this?

$str = 'test';
$str = preg_replace('@(.*)@isu', '\<$1', $str);
echo $str;

EDIT Since it’s been discovered you can view the <test in the source code of a browser, I adjusted my code as follows to make the output human readable in a browser:

$str = 'test';
$str = preg_replace('@(.*)@isu', "<$1", $str);
echo '<pre>';
echo htmlentities($str);
echo '</pre>';

But that outputs:

<test<

As the user anubhava explains, you can add a 1 to the end of the preg_replace to return only the first match:

$str = preg_replace('@(.*)@isu', "<$1", $str, 1);

Which would then output the following which is what the original poster desires:

<test

Use line start and end anchors in your regex:

$str = 'test';
$str = preg_replace('@^(.*)$@isu', '<$1', $str);
echo $str;

OR use .+:

$str = preg_replace('@(.+)@isu', '<$1', $str);

OR with .* specify max replacement count:

$str = preg_replace('@(.*)@isu', '<$1', $str, 1);

OUTPUT:

<test

Problem is by using .* preg_replace is matching and replacing the input string twice, once for the whole input string and once for the end (empty string).