php:preg_match 和 preg_replace

php: preg_match and preg_replace

我不确定如何执行以下操作...

我需要搜索 string 并匹配 forward slashcertain letters 的所有实例。这是针对用户可以输入的单词修改,我希望他们能够修改单个单词。

这是一个示例字符串

Hello, isn't the weather just absolutely beautiful today!?

我希望用户能够做的是这样的事情

Hello, isn't the /bo weather just /it beautiful today!?

注意 /bo/it

我想做的是有一个 preg_match 和/或 preg_replace 语句来查找和替换 /bo/it 的实例并转换它们进入 html 标签,例如 bolded html tagitalics html tag(我不能在这里输入它们,否则它们会被转换成实际的 html。但紧跟在 [=17 之后的单词周围=] 所以在这个例子中它最终会成为

Hello, isn't the <b>weather</b> just <i>beautiful</i> today!?

有什么想法可以用 regex 做到这一点吗?

转换完成后,我将在将数据连同准备好的语句插入数据库之前进行标准清理。

正则表达式

/\/(bo|it)\s+([\S]+)(?=\b)/g

和替换字符串

<></>

几乎会这样做:

Hello, isn't the <bo>weather</bo> just <it>beautiful</it> today!?

但是标签还不是很正确...它们需要是单个字母。 :-(

在这里试试:https://regex101.com/r/oB9gT0/1

2。编辑 - 有点晚了,但现在可以了:

$str=preg_replace('/\/([bi])((?<=b)o|(?<=i)t)\s+([\w]+)/','<></>',$str);

现在将提供正确的结果:

Hello, isn't the <b>weather</b> just <i>beautiful</i> today!?

看这里:https://regex101.com/r/oB9gT0/3

$string = "Hello, isn't the /bo weather just /it beautiful /bo today!?";

var_dump(preg_replace (array('/\/bo\s(\w+)/', '/\/it\s(\w+)/'), array('<b></b>', '<i></i>'), $string));

"Hello, isn't the weather just beautiful today!?"

您可以使用 preg_replace_callback 来达到这个目的。
这基本上会为发生的每个匹配调用一个回调方法。
在回调里面,你可以根据你的条件进行替换
(粗体为bo,斜体为it,heading为he et al.)

像这样 -

$str = "Hello, isn't the /bo weather just /it beautiful today!?";
$regex = "/\/(.*?)\s+(.+?)\b/";

function callback($matches){
    $type = $matches[1];
    $text = $matches[2];
    switch($type){
        case "bo":
            return "<b>".$text."</b>";
            break;
        case "it":
            return "<i>".$text."</i>";
            break;
        default:
            return $text;
    }   
}

$resp = preg_replace_callback(
    $regex,
    "callback",
    $str
);

var_dump($resp);

/*
OUTPUT- 
Hello, isn't the <b>weather</b> just <i>beautiful</i> today!?
*/

可以通过检查各种类型和无效类型来进一步扩展此示例