我有string
这样:
$str = "<div>
<b>
<label>Company-Name : Anything</label>
</b>
</div>
<div>
<b>
<label>First-Name : Alex</label>
</b>
</div>
<div>
<b>
<label>Cell-Phone : 035123913</label>
</b>
</div>";
现在我想要这个数组:
$arr = array ("Company-Name"=>"Anything",
"First-Name"=>"Alex",
"Cell-Phone"=>"035123913");
我该怎么做?
据我通过搜索意识到,有一个删除所有html标签的功能:
strip_tags($str);
我认为以上功能是一个线索。还有两个不变的字符:\n
和:
。我想我们可以用它们来爆炸结果。 (但我不确定,也许我错了)
答案 0 :(得分:2)
您可以使用双@hrs_staff_by_client = TaskLog.joins(:staff).joins(:client).joins(:user).select("staffs.full_name AS full_names").select("staffs.position AS positions").select("clients.full_name AS client_names").select("users.email AS emails").select("clients.*, SUM(task_logs.total_hrs) AS today").group("staffs.id, users.id, clients.id")
。
explode
在我猜的所有情况下,您可能需要$str = explode(PHP_EOL, $str);
$arr = array();
foreach ($str as $val) {
$arr[] = explode(":", $val);
}
。
答案 1 :(得分:2)
我喜欢strip_tags方法,但这是一个正则表达式:
$str = "<div>
<b>
<label>Company-Name : Anything</label>
</b>
</div>
<div>
<b>
<label>First-Name : Alex</label>
</b>
</div>
<div>
<b>
<label>Cell-Phone : 035123913</label>
</b>
</div>";
preg_match_all('/<label>(.*)<\/label>/', $str, $matches);
foreach($matches[1] as $match) {
$parts = explode(':', $match);
$results[trim($parts[0])] = trim($parts[1]);
}
var_dump($results);
输出:
array (size=3)
'Company-Name' => string 'Anything' (length=8)
'First-Name' => string 'Alex' (length=4)
'Cell-Phone' => string '035123913' (length=9)
答案 2 :(得分:1)
这解决了问题,建立在@Praveen Kumar先前的答案
之上$str = explode(PHP_EOL, $str);
$arr = [];
foreach ($str as $val) {
$pos=strpos($val, ":");
if ($pos !== false)
{
$arr[] = explode(":", strip_tags($val));
}
}
foreach($arr as $key=>$value){
$final_array[trim($value[0])] = trim($value[1]);
}
var_dump($final_array);
输出
array (size=3)
'Company-Name' => string 'Anything' (length=8)
'First-Name' => string 'Alex' (length=4)
'Cell-Phone' => string '035123913' (length=9)
答案 3 :(得分:1)
获得所需结果(不剥离标签)的一种较短方法是使用正则表达式:
preg_match_all( "{<label>([^:]+) +: +([^<]+)</label>}", $str, $matches );
通过这种方式,在$matches
数组中,您将获得:
Array
(
[0] => Array
(
[0] => <label>Company-Name : Anything</label>
[1] => <label>First-Name : Alex</label>
[2] => <label>Cell-Phone : 035123913</label>
)
[1] => Array
(
[0] => Company-Name
[1] => First-Name
[2] => Cell-Phone
)
[2] => Array
(
[0] => Anything
[1] => Alex
[2] => 035123913
)
)