如何将字符串中的所有数字替换为连字符


How to replace all numbers with hyphens in the string?

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

示例:

(英文版)

$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);

我还没有测试过波斯语变体,因为我没有RTL脚本的经验,但它应该适用于英语示例。

// first let's put all the numbers to a new line
$digit_split_str = preg_replace('/(?<!^)(?='d)/', "'n", $str);
// then ampersands
$ampersand_split_str = preg_replace('/(?<!^)&/', "'n&'n", $digit_split_str);
// then let's replace the numbers at the start of the string with dashes
$dashed_str = preg_replace('/^'d+/m', "- ", $ampersand_split_str);

编辑:修复了与号和换行符之间的角案例。。。