简体   繁体   中英

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

['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

The shortest one with preg_split function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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