I have the following string in a text file:
^b^B
I'm trying to split this into two variables. My current code is using explode()
but it does not work as I want it to:
$num1 = '^b';
$num2 = '^B';
How can I accomplish this using PHP?
THIS IS MY CODE
<?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>
Use preg_split()
with a lookaround assertion:
list($num1, $num2) = preg_split('/(?<=\^b)/', $str);
Autopsy:
/
- starting delimiter(?<=
- start of positive lookbehind (meaning "if preceded by")\^b
- match literal characters ^b
)
- end of positive lookbehind/
- ending delimiterVisualization:
In plain english, it means: split on places where it's preceded by a ^b
and assign the array values to the variables $num1
and $num2
using the list
construct.
Use preg_match_all():
<?php
$str = '^b^B';
preg_match_all('/(\^.)/', $str, $matches);
var_dump($matches);
#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];