我在文本文件中有以下字符串:
^b^B
我试图把它分成两个变量。我当前的代码正在使用explode()
,但它无法正常工作:
$num1 = '^b';
$num2 = '^B';
如何使用PHP实现此目的?
这是我的代码
<?php
if(isset($_POST['refresh'])) {
exec('/var/www/www.rfteste.com/htdocs/estado.sh');
}
if(isset($_POST['on'])) {
exec('/var/www/www.rfteste.com/htdocs/on.sh');
}
if(isset($_POST['off'])) {
exec('/var/www/www.rfteste.com/htdocs/off.sh');
}
echo "<H3>CONTROL PANEL</H3>";
$str = file_get_contents("/var/www/www.rfteste.com/htdocs/refresh.txt");
$vals = explode("^", $str);
$num1 = "^".$vals[0];
$num2 = "^".$vals[1];
$onoff= "^A";
if($num2 == $onoff)
echo "<b>on</b>";
else
echo "<b>off</b>";
?>
<html>
<body>
<form method="post" action="">
<p>
<center><input type="submit" value="on" name="on""';" /></center>
<center><input type="submit" value="off" name="off""';" /></center>
<center><input type="submit" value="refresh" name="refresh""';" /></center>
答案 0 :(得分:4)
使用preg_split()
查看断言:
list($num1, $num2) = preg_split('/(?<=\^b)/', $str);
<强>尸检:强>
/
- 开始分隔符(?<=
- 开始积极的观察(意思是“如果前面有”)
\^b
- 匹配文字字符^b
)
- 结束积极的外观/
- 结束分隔符<强>可视化:强>
简单来说,它意味着:在^b
前面的地方进行拆分,并使用list
构造将数组值分配给变量$num1
和$num2
答案 1 :(得分:1)
<?php
$str = '^b^B';
preg_match_all('/(\^.)/', $str, $matches);
var_dump($matches);
答案 2 :(得分:1)
#Pull all of the contents of file, myfile.txt, into variable, $str
$str = file_get_contents("myfile.txt");
#split up the data in $str, at every instance of '^'.
$vals = explode("^", $str);
#now $vals is an array of strings
#concatenate the "^" back into the strings as they were removed by explode.
$num1 = "^".$vals[0];
$num2 = "^".$vals[1];