I am having a file like this and I am trying to replace the file:
abc.txt
# Define the right-hand side of the equation:
#{xvalue1#}xval1= ;#xvalue1
#{xvalue2#}xval2= ;#xvalue2
What I did is as follows:
$myfile = fopen("abc.txt", "r") or die("Unable to open file!");
$data = fread($myfile,filesize($pgm_file));
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$parsed0 = get_string_between($data, "#{xvalue1#}xval1=", ";#xvalue1");
$parsed1 = get_string_between($data, "#{xvalue2#}xval2=",";#xvalue2");
I am trying to replace the values as follows:
$datanew0 = str_replace($parsed0,"5", $data);
$datanew1 = str_replace($parsed1,"10", $datanew0);
When I echoed echo $datanew1;
I am getting output as :
# Define the right-hand side of the equation:
#{xvalue1#}xval1= 5;#xvalue1
#{xvalue2#}xval2= 5;#xvalue2
My expected result is:
# Define the right-hand side of the equation:
#{xvalue1#}xval1= 5;#xvalue1
#{xvalue2#}xval2= 10;#xvalue2
I'd recommend to rather work with the positions within the string than extracting and replacing stuff.
Take a look at this example
function injectBetween($what, $start, $end, $src){
$lpos = strpos($src, $start);
$rpos = strrpos($src, $end);
return substr($src, 0, $lpos + strlen($start)) . $what . substr($src, $rpos);
}
var_dump(injectBetween('test', 'start', 'end', 'startend'));
Will give you string 'starttestend' (length=12)
Or to match your example:
var_dump(injectBetween('5', '#{xvalue1#}xval1= ', ';#xvalue1', '#{xvalue1#}xval1= ;#xvalue1'));
I don't know how your full input looks like. If you have multiple lines that have the same pattern this will most probably fail. Better use regular expressions in that case or parse your input line by line (using explode()).
Why not using RegEx ? it is more appropriate, efficient and maintainable implementation :
<?php
$subject = "#{xvalue1#}xval1= 19;#xvalue1";
$pattern = "/#\{xvalue[0-9]+#\}xval[0-9]+= ([0-9]+);#xvalue[0-9]+/";
preg_match_all($pattern, $subject, $matchs);
var_dump($matchs);
EDIT:
I suggest you to change your pattern like this :
#{xvalue#}xval1= ;#xvalue
And the RegEx pattern will be :
$pattern = "/#\{xvalue#\}xval([0-9]+)= ([0-9]+);#xvalue/";
Note that i have also captured the key associated to your value
Related
I Am working on a project that requires me to find all of the functions across several hundreds of php files, and return the line number that the function was first created on, as well as the line number that the function closes on. The entire file is loaded in as a string, and each line within the file begins with a line number. I have found the number that the functions start on, and have in variables the function name, meaning that i can establish a pattern, but cant seem to narrow down a way to figure out where it ends.
A portion of the string may look something like this:
Line11 blah blah blah Line12 function doSomething ( $foo, $fab ) Line13 { Line14 ... Line15 { Line16 ... Line18 ... Line19 ... Line21 if (... ) Line22 ... ( ... ); Line23 break; Line24 } Line25 die ( ... ); Line26 } Line27 Blah Blah Blah
In this case, I would need to know that the function ends on line 26.
Ive tried using a function to get the number by matching reliable patterns on each side of it:
function for finding strings between patterns:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$name = 'doSomething';
$paradigm = '$foo, $fab';
$start = 12;
$mess = 'Line'.$start.'function'.$name.'('.$paradigm.')'.'/\{([^{}]|(?R))*\}/'.' Line';
$lineNum = get_string_between($string, $mess, ' ');
echo $lineNum;
I was expecting an output of 26, but currently, it doesn't return anything.
how to extract specific string after specific word using html dom in php. I have
<div class="abc">
<script type="text/javascript">
var flashvars = { word : path } </script>
Now i want to extract path after word
thanks for your response.
I got the solution for what i was looking.
Here is the code in case someone needs it.
Explanation :
'$results' is the curl response.
Enter div class name (which you want to fetch) inside "$xpath->query() function"
You will get source code for entire class inside "$tag->textContent"
$dom = new DOMDocument();
$dom->loadHTML($results);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[#class="e"]');
foreach ($tags as $tag)
{
echo "<br>----------<br>";
var_dump($tag->textContent);
echo "<br>----------<br>";
}
Now you have your required class' html source inside "$tag->textContent".
Now you can fetch anything from the string between "start" and "end" points using below function.
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
In my case i used it like this :
$price = get_string_between($tag->textContent,'swf', '+');
echo $price;
Here "swf" is the starting point of the path and "+" is the end point.
Hope it saves somebody else time :)
I have been working on a script that pulls information from a certain website. The said website pulls the information from a database and displays it in a way the user can easily read it (like always).
Imagine it looks like this:
Var1: result1
Var2: result2
Var3: result3
What my script does is that it reads the page's source code and retrieves "result1", "result2" and "result3" by obtaining the text between two strings.
Sample code:
<?php
function get_string_between($string, $start, $end) {
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
function check($url) {
// usually, $fullstring = file_get_contents($url);
$fullstring = "<string1>result1</string1><string1>result2</string1><string1>result3</string1>";
$result = get_string_between($fullstring, "<string1>", "</string1>");
echo "<b>Result: </b>".$result;
}
check("random"); // just to execute the function
?>
In case you wonder why I have the check() function there it is because this code is part of something bigger and I need a solution that works in this case scenario, so I tried to keep it immaculate.
Now, I can easily get "result1" because it's the first occurrence, but how can I get "result2" and "result3"?
Thank you :)
Use a regex to extract all of the matches, then pick the ones you want:
function get_string_between($string, $start, $end)
{
preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
return $matches[1];
}
The regex will capture anything between the $start and $end variables.
Now the function returns an array of all of the result values, which you can pick which one you want:
list( $first, $second, $third) = get_string_between( $string, "<string1>", "</string1>");
You can see it working in this demo.
I have an XML file which is as follows. I want to parse this XML file using PHP.
<id_list>
-
<ids>
<id>195002349</id>
<id>374487611</id>
<id>192983648</id>
<id>168378766</id>`
<id>161573001</id>
</ids>
<next_cursor>0</next_cursor>
<previous_cursor>0</previous_cursor>
</id_list>
I want the output in the form:
Id1=195002349 Id2=374487611 Id3=192983648 Id4=168378766 Id5=161573001
When reading the XML (with SimpleXMLElement($file)), use XPath to search for "ids", and do a while loop to read the element`s text.
Like so:
$notes = new SimpleXMLElement('test2.xml', NULL, true);
$all = array();
$results = $notes->xpath("/id_list/ids/id");
foreach($results as $to){
echo "<br>".$to;
$all[]=(string)$to;
}
print_r($all);
This is a handy little function to strip out a string between two specified pieces of text. This could be used to parse XML text, bbCode, or any other delimited code/text for that matter.
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
How would you return part of a string based on the contents of the string in php. Unlike substr() and related functions where you use an integer length
So if we are given a string like this
here is a nice string that is being used as an example
How could we return a string like this
nice string
Somehow we have to pass the function a and that so it knows the start and end point. It will find the first a and then start keeping track of characters then when it finds that it will stop, and return.
To be clear: we know the contents of the original string... and the arguments sent.
Use this function:
function get_string_between($string, $start, $end)
{
$ini = strpos($string,$start);
if ($ini == 0)
return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$input = 'here is a nice string that is being used as an example';
$output = get_string_between($input, 'a', 'that');
echo $output; //outputs: nice string
You could use regular expressions too with preg_match:
<?php
function get_string_between($string,$start,$end) {
preg_match("/\b$start\b\s(.*?)\s\b$end\b/",$string,$matches);
return $matches[1];
}
$str = "here is a nice string that is being used as an example";
print get_string_between($str,"a","that")."\n";
?>