php - 带模式的php格式字符串
问题描述
我有一个字符串(修剪),我想根据预定义的模式拆分这个字符串。我写了一个可能更具解释性的代码。
$string="123456789";
$format=['XXX','XX','XXXX'];
$formatted="";
foreach ($format as $cluster){
$formattedCluster=substr($string,0,strlen($cluster));
$string=substr($string,strlen($cluster));
$formatted.=$formattedCluster.' ';
}
$formatted=substr($formatted, 0, -1);
dd($formatted);
//outputs: "123 45 6789"
如您所见,它接受一个没有任何空格的字符串,并$format
在这种情况下根据模式将其用空格分隔。该模式是一个数组。
一个伪例子:
$str='qweasdzxc'
$pattern=['X','X','XXXX','XXX']
$formatted='q w easd zxc'; //expected output
它按预期工作,但相当可怕。这个问题的正确解决方案是什么?正确性是指速度和可读性。
环境:PHP 7.4,Laravel 8
解决方案
我会使用https://www.php.net/manual/en/function.vsprintf.php得到结果:
$str='qweasdzxc';
$pattern='% % %%%% %%%'; // ['X','X','XXXX','XXX']
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));
推荐阅读
- react-native - 是否可以等待组件渲染?React 测试库/Jest
- javascript - 使用 jQuery.ajax 每隔一段时间从外部文件返回文本
- wpf - WPF - 将启动窗口添加到项目后无法关闭应用程序
- angular - 从 HTML 调用函数到打字稿不等待完成
- python - 熊猫数据框上的循环和条件
- autodesk-forge - 本地化 Autodesk Forge 扩展按钮
- sql - 这可以在没有联合运算符的情况下重写吗?
- python - 如何使用 pysimplegui 添加控制台以在布局字段中显示结果
- kivy - 是否可以在轮播中使用滑块?
- airflow - 气流在容器中运行时如何使用气流配置文件(airflow.cfg)?