简体   繁体   English

搜索字符串并在PHP中创建一个数组

[英]Search in a string and create an array in PHP

How to convert this string 如何转换这个字符串

 *|text:student:required|* 

( * and | is part of string ) into array like this (*和|是string的一部分)像这样进入数组

['text' ,'student','required']  

Here you go: 干得好:

$str = "|text:student:required|";
$str = trim($str,"|");
$str = trim($str,"*");
$x = explode(':',$str);
print_r($x);die;

try the following: 尝试以下方法:

$str = '*|text:student:required|*';
$str = preg_replace("/[|*]/", '', $str);
$arr = explode(':', $str);

this simply removes the | 这只会删除| AND * from the string using preg_replace() and the turns the string into an array using explode AND *使用preg_replace()从字符串开始,并使用explode将字符串转换为数组

The shortest one with preg_split function: 最短的一个带有preg_split函数:

$s = '*|text:student:required|* ';
$result = preg_split('/[*:| ]+/', $s, -1, PREG_SPLIT_NO_EMPTY);

print_r($result);

The output: 输出:

Array
(
    [0] => text
    [1] => student
    [2] => required
)
$string = "*|text:student:required|";
$string = str_replace("*", "", str_replace("|","", $string));
$array = explode(':', $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM