首页 > 解决方案 > 字符串用 PHP 替换文本

问题描述

我有

$text = '--ACT-- active --INA-- inactive';

我想用我所做的值替换--ACT-- 和--INA--:

str_replace(array('--ACT--','--INA--'), array('<div class="wp"><b>1</b></div>','<div class="wp"><b>2</b></div>'), $text);

结果是

<div class="wp"><b>1</b></div> Active
<div class="wp"><b>2</b></div> inactive

但我想在 div 内而不是在 div 外添加活动非活动文本,例如:

<div class="wp"><b>1</b> active</div>

我不想在 str_replace 中添加这个文本,我想从 $text 变量中获取它,有什么帮助吗?

标签: php

解决方案


使用 preg_replace 并捕获 ACT/INA 之后的单词并将 html 放在它周围。

$text = '--ACT-- active --INA-- inactive';

// Add html to active
$text = preg_replace("/--ACT-- (\w+)/" , '<div class="wp"><b>1</b>$1</div>',$text);

// Add html to inactive and echo
Echo preg_replace("/--INA-- (\w+)/" , '<div class="wp"><b>2</b>$1</div>',$text);

https://3v4l.org/DdaFt

这假设它只是 ACT 之后的一个单词。如果这不正确,请使用更相关的示例更新您的问题。


推荐阅读