php - 字符串用 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 变量中获取它,有什么帮助吗?
解决方案
使用 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);
这假设它只是 ACT 之后的一个单词。如果这不正确,请使用更相关的示例更新您的问题。
推荐阅读
- go - 从 URL 查询参数解码 JSON
- node.js - 在 Express Nodejs 中记录用户活动
- angular - Angular Slickgrid - 基于网格数据加载单选编辑器集合
- java - Java 8 2 个不同列表的比较
- mule - Dataweave 2.0 中的 Excel 到 Json 映射
- mysql - SQL:检测多个相同的条目作为一个批次
- marklogic - 当任务服务器负载不足时,减少延迟或优先处理应用服务器 (XDBC/HTTP) 上的传入请求
- stm32 - 如何在 stm32 上使用 SPI 将 32 位字传输到 GPS 接收器芯片 (MAX2769C)
- salesforce - 将签名版本的文档存储在 salesforce 中
- json - 如何在 .testcaferc.json 中使用任何 json 或数组或任何 js 文件?