在 php 中替换两个字符(特殊符号)之间的字符串

问题描述 投票:0回答:4

我有一个像这样的字符串:He

*is*
a good boy。怎么
*are*
你。然后我想用输入类型替换isaretextbox意味着替换星号(*)之间的东西。我怎样才能得到这个请帮帮我。

php string substring
4个回答
1
投票
<?php
    $buffer = 'He *is* a good boy. How *are* you.';
    echo "Before: $buffer<br />";
    $buffer = preg_replace_callback('/(\*(.*?)\*)/s', 'compute_replacement', $buffer);
    echo "After: $buffer<br />";

    function compute_replacement($groups) {
        // $groups[1]: *item*
        // $groups[2]: item
        return '<input type="text" value="'.$groups[2].'" />';
    }
?>

结果:


1
投票

试试这个,

<?php
$x="hai, *was/is* are you, is this *was* test ";
echo preg_replace("/\*[\w\/]*\*/","",$x);
?>

0
投票

使用

preg_replace()
;例如:

<?php

$pattern = '/\*\w+\*/';
$string  = 'he *is* a good boy';
$replacement = 'was';

echo preg_replace($pattern, $replacement, $string);

产量:

他是个好孩子


0
投票

这样试试:

$txt = "He *is* a good boy. How *are* you.";
$_GET['one'] = "doesn't";
$_GET['two'] = "think about";

preg_match_all( '{\*[^*]+\*}',$txt,$matches );
$txt = str_replace( $matches[0][0], $_GET['one'], $txt );
$txt = str_replace( $matches[0][1], $_GET['two'], $txt );

echo $txt;

3v4l.org 演示

或者,用

preg_replace
,这样:

$txt = preg_replace
(
    '/^(.*)\*[^*]+\*(.*)\*[^*]+\*(.*)$/',                  # <-- (Edited)
    "\\1{$_GET[one]}\\2{$_GET[two]}\\3", 
    $txt 
);
© www.soinside.com 2019 - 2024. All rights reserved.