我有一个显示
字符串的网站"Requires 10MB data",
"Requires 700MB data",
"Requires 1.2GB data" etc.,
我正试图找到一种方法来加强 10MB 或 700MB 或 1.2GB 部分。
这会导致
"Requires <b>10MB</b> data",
"Requires <b>700MB</b> data",
"Requires <b>1.2GB</b> data" etc.,
我曾经滥用谷歌一段时间但不知道要搜索什么。
非常感谢任何帮助!
答案 0 :(得分:1)
您可以preg_match
删除GB / MB之前的号码:
$replaced = preg_match('[0-9.]+[GM]B', $str, $m);
var_dump($m[0]);
[0-9.]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible
0-9 a single character in the range between 0 and 9
. the literal character .
[GM] match a single character present in the list below
GM a single character in the list GM literally (case sensitive)
B matches the character B literally (case sensitive)
答案 1 :(得分:1)
或者,如果你不喜欢正则表达式,或者没有看到需要加载一个完整的正则表达式库,这个简单的尝试:
$t = 'Requires 10MB data';
$t = str_replace( array('Requires ', ' data') , '', $t);
应该只留下10Mb或1.2GB的字符串部分。
答案 2 :(得分:0)
也许我太简单但......
$str = str_replace('B data', 'B', str_replace('Requires ', $original_str);
答案 3 :(得分:0)
如果您要搜索并更换MB / GB部件,可以使用preg_replace
方法:
$string = preg_replace($pattern, $replacement, $subject);
然后,你的方法看起来像这样。
$string = 'Requires 340MB of space.';
$string = preg_replace('/([0-9.]+[KMGT]B)/', '<b>$1</b>', $string);
echo $string; // Outputs "Requires <b>340MB</b> of space."