php - 如何用字符串中的连字符替换所有数字?

标签 php regex

我用一个例子来解释我的问题:

示例:

(英文版)

$str = '1 healthy, fine, sound 2 tip-top, fit, robust, sturdy & 1  substandard, poor';

我想要这个输出:

- healthy, fine, sound
- tip-top, fit, robust, sturdy
&
- substandard, poor

(波斯语版本) - 从右边开始

$str ='1 خشكاندن، خشكانيدن 2رطوبتزدايي كردن، نمزدايي كردن & تر کردن';

我想要这个输出:

- خشكاندن، خشكانيدن
- رطوبتزدايي كردن، نمزدايي كردن
&
تر کردن

我知道,这个例子中的 1 确实很模糊。但实际上它是右边的第一个字符。但是在 SO 中,因为波斯语没有正确的方向,所以 1 在左边。


注意:可能没有数字,甚至没有&。在这种情况下,我不想要任何改变..!

$str = 'healthy, fine, sound, tip-top'; // I want this: healthy, fine, sound, tip-top


$str = 'healthy, fine, sound & poor'; /* I want this: healthy, fine, sound
                                                      &
                                                       poor
                                      */

我可以使用多个 str_replace() 来做到这一点。但我想知道,是否可以使用 REGEX 来做到这一点?

最佳答案

此脚本适用于英语和波斯语变体。

$str = "1 خشكاندن، خشكانيدن 2رطوبتزدايي كردن، نمزدايي كردن & تر کردن";
// $str = '1 healthy, fine, sound 2 tip-top, fit, robust, sturdy & 1  substandard, poor';
$dashed_line = preg_replace("/[0-9]+/", "- ", $str);
$lines = preg_replace("/(?<!^)- /", "\n- ", $dashed_line);
$lines_with_and = preg_replace("/&/", "\n&\n", $lines);
$lines_with_and_single_space = preg_replace("/ +/", " ", $lines_with_and);
echo preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $lines_with_and_single_space);

关于php - 如何用字符串中的连字符替换所有数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34325337/

相关文章:

regex - 如何使用Go regexp查找与特定模式和捕获组的所有匹配项

php - Kohana ORM,在模型中定义字段

php - 如何在页面上仅显示选定数量的数据库条目

php - 使用php调用存储过程

php - 将多个复选框插入数据库列

javascript - 从抓取的 HTML 中提取 Javascript 对象的正则表达式

javascript - ajax 调用中的数据是如何计算的?

javascript - 返回字符串是否包含有效字符

python - python中的正则表达式操作

javascript - Mozilla 雷鸟 "FiltaQuilla"; JavaScript 和正则表达式