Php 将排序转换为自定义排序
我会尽我所能解释这件事,如果这件事已经发生了,我会道歉 我试图以定义的顺序替换段落中的某些字符串 该段:Php 将排序转换为自定义排序,php,arrays,sorting,Php,Arrays,Sorting,我会尽我所能解释这件事,如果这件事已经发生了,我会道歉 我试图以定义的顺序替换段落中的某些字符串 该段: $Paragraph = "This bit of Water has an Apple, a pseudo Apple; some Rubber and a Big Rubber too."; 我有一个字符串数组: $SortableArray = array( "Apple"=>"Green Apple",
$Paragraph = "This bit of Water has an Apple, a pseudo Apple; some Rubber and a Big Rubber too.";
我有一个字符串数组:
$SortableArray = array(
"Apple"=>"Green Apple",
"Big Rubber"=>,"Big Gasket"
"Rubber"=>"Gasket",
"pseudo Apple"=>"Banana",
"Water"=>"Blue Water"
);
因此,我必须按照键的相反顺序对其进行排序,以尝试捕获伪苹果:
$SortableArray = array(
"Water"=>"Blue Water",
"pseudo Apple"=>"Banana",
"Rubber"=>"Gasket",
"Big Rubber"=>,"Big Gasket"
"Apple"=>"Green Apple"
);
但这会导致ruber/Big ruber
字符串出错
这片蓝色的水域有一个绿色的苹果,一个香蕉;某个人
垫圈和一个大的单垫圈也
当我需要确保在重新使用数组时,Big Rubber
位于Rubber
之前,以获得以下结果时,我有点卡住了:
$Paragraph = "This bit of Water has an Apple, a pseudo Apple; some Rubber and a Big Rubber too.";
$SortableArray = array(
"Water"=>"Blue Water",
"pseudo Apple"=>"Banana",
"Big Rubber"=>"Big Gasket",
"Rubber"=>"Single Gasket",
"Apple"=>"Green Apple"
);
foreach ($SortableArray as $Find=>$Replace){
$Paragraph = str_replace($Find, $Replace, $Paragraph);
}
echo $Paragraph;
这片蓝色的水域有一个绿色的苹果,一个香蕉;某个人
垫圈和一个大垫圈
提前感谢使用并按键长度排序(从最长到最短):
在foreach
循环之前添加此项,我将得到以下输出:
这片蓝色的水域有一个绿色的苹果,一个香蕉;一些单垫圈和一个大垫圈
按键长度使用和排序(从最长到最短):
在foreach
循环之前添加此项,我将得到以下输出:
这片蓝色的水域有一个绿色的苹果,一个香蕉;一些单垫圈和一个大垫圈
这是2参数形式的完美匹配,它首先替换最长的关键点:
$Paragraph = "This bit of Water has an Apple, a pseudo Apple; some Rubber and a Big Rubber too.";
$SortableArray = array(
"Apple"=>"Green Apple",
"Rubber"=>"Single Gasket",
"pseudo Apple"=>"Banana",
"Big Rubber"=>"Big Gasket",
"Water"=>"Blue Water"
);
echo strtr($Paragraph, $SortableArray);
输出:
这片蓝色的水域有一个绿色的苹果,一个香蕉;某个人
垫圈和一个大垫圈
这是2参数形式的完美匹配,它首先替换最长的键:
$Paragraph = "This bit of Water has an Apple, a pseudo Apple; some Rubber and a Big Rubber too.";
$SortableArray = array(
"Apple"=>"Green Apple",
"Rubber"=>"Single Gasket",
"pseudo Apple"=>"Banana",
"Big Rubber"=>"Big Gasket",
"Water"=>"Blue Water"
);
echo strtr($Paragraph, $SortableArray);
输出:
这片蓝色的水域有一个绿色的苹果,一个香蕉;某个人
垫圈和一个大垫圈
谢谢你,伙计。这就是我想要的逻辑。我需要对数组进行排序,所以这是我要找的正确答案。@JustBaron,虽然我很喜欢绿色的复选标记,但Nick的答案更干净,而且是“开箱即用”的。谢谢你,伙计。这就是我想要的逻辑。我需要对数组进行排序,所以这是我正在寻找的正确答案。@JustBaron,虽然我很喜欢绿色的复选标记,但Nick的答案更干净,而且是“开箱即用”的