Php preg#u replace不';无法按预期使用数字字符串数据

Php preg#u replace不';无法按预期使用数字字符串数据,php,regex,preg-replace,Php,Regex,Preg Replace,在处理以数字字符开头的字符串时,我注意到一种奇怪的preg_replace()行为:替换字符串的第一个字符(第一个数字)被截断。我在PHP5.6.36和PHP7.0.30中看到了它 此代码: <?php $items = array( '1234567890' => '<a href="http://example.com/1234567890">1234567890</a>', '1234567890 A' => '<a h

在处理以数字字符开头的字符串时,我注意到一种奇怪的
preg_replace()
行为:替换字符串的第一个字符(第一个数字)被截断。我在PHP5.6.36和PHP7.0.30中看到了它

此代码:

<?php

$items = array(
    '1234567890'   => '<a href="http://example.com/1234567890">1234567890</a>',
    '1234567890 A' => '<a href="http://example.com/123456789-a">1234567890 A</a>',
    'A 1234567890' => '<a href="http://example.com/a-1234567890">A 1234567890</a>',
    'Only Text'    => '<a href="http://example.com/only-text">Only Text</a>',
);

foreach( $items as $title => $item ) {
    $search = '/(<a href="[^"]+">)[^<]+(<\/a>)/';
    $replace = '$1' . $title . '$2';

    // Preserve for re-use.
    $_item = $item;

    // Doesn't work -- the titles starting with a number are wonky.
    $item = preg_replace( $search, $replace, $item );
    echo 'Broken: ' . $item . PHP_EOL;

    // Ugly hack to fix the issue.
    if ( is_numeric( substr( $title, 0, 1 ) ) ) {
        $title = ' ' . $title;
    }
    $replace = '$1' . $title . '$2';
    $_item = preg_replace( $search, $replace, $_item );
    echo 'Fixed:  ' . $_item . PHP_EOL;
}

似乎是我的
$replace
参数(
'$1'.$title'.$2'
)造成的。由于$title以数字开头,它被添加到$1,因此
$replace
看起来像
$11234…$2

解决方案:

$replace = '$1%s$2';
.
.
.
echo sprint( $item, $title );

…它的优点是不会在我的页面标题链接中引入假空格。

似乎应该归咎于我的
$replace
参数(
'$1.$title.$2'
)。由于$title以数字开头,它被添加到$1,因此
$replace
看起来像
$11234…$2

解决方案:

$replace = '$1%s$2';
.
.
.
echo sprint( $item, $title );

…其优点是不会在我的页面标题链接中引入虚假空格。

为了避免这种行为,只需将
$1
更改为
${1}
,与
$2
相同

foreach( $items as $title => $item ) {
    $search = '/(<a href="[^"]+">)[^<]+(<\/a>)/';
    $replace = '${1}' . $title . '${2}';
    ...
foreach($items作为$title=>$item){

$search='/(为了避免这种行为,只需将
$1
更改为
${1}
,与
$2
相同

foreach( $items as $title => $item ) {
    $search = '/(<a href="[^"]+">)[^<]+(<\/a>)/';
    $replace = '${1}' . $title . '${2}';
    ...
foreach($items作为$title=>$item){

$search='1/(进一步的检查使我认为替换是问题所在,即,
“$1”。“1234…”。“2”
被解释为
$11234…$2
。进一步的检查使我认为替换是问题所在,即,
“$1”。“1234…”。“2”
被解释为
$11234…$2
。比我丑陋的h好得多。)谢谢!…让我感到尴尬的是,这在上的第一个例子中已经提到了。比我丑陋的黑客好多了。谢谢!…让我尴尬的是,这在上的第一个例子中已经提到了。