My 1 file is city.html which contains the following code
<script language="javascript">alert("Page Called"); </script>
'Bhubaneshwar', 'Orissa', 'India'
My another file index.php contains the following code
$x=file_get_contents("city.html");
$x=array($x);
echo $x[0];
It shows the following output
'Bhubaneshwar', 'Orissa', 'India'
But I want single word output like this.
When I print $x[0], it should be Bhubaneshwar
When I print $x[1], it should be Orissa
When I print $x[2], it should be India
First you need to remove script tags
$x = file_get_contents("city.html");
$x = preg_replace('%<script[^>]*>.*?</script>%/m', '', $x);
and then you can use explode:
$array = explode(',', $x);
then you can trim and remove quotes:
$array = array_map(function($item) {
return preg_replace("/^'|'$/", trim($item));
}, $array);
Use explode to convert string to array:-
// Remove script tag
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $x);
// $string = str_replace(' ', '', $string); // Remove space from string
$string = preg_replace('/\s+/', '', $string); // Remove whitespace from string
// explode string
$x = explode(',',$string);
Hope it will help you :)
Try,
$x=file_get_contents("city.html");
$x=array($x);
$html = preg_replace('#<script[^>]*?.*?</script>#', '', $x);
$str = str_replace(', ', ',', $html);
$x = explode(',',trim($str[0]));
$remove[] = "'";
$result = str_replace( $remove, "", $x );
foreach($result as $cities)
{
echo $cities . "<br>";
}
Here is code that first removes the preceding script tag(s) and breaks down the remainder into an array:
$x=array_pop(explode('</script>', $x));
$x=preg_split("/'\s*,\s*'/", trim(trim($x), "'"));
The first of those two statements is only needed if you keep that script tag inside your HTML, which seems to be there for testing only.
To display the result, you could do this:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
Considerations
It is unusual to have such data format inside HTML files. HTML is intended for rendering data in a user-friendly manner, and that representation does not really fit.
If you are the creator of the HTML file, then consider moving to a JSON format. In that case your file would be named city.json and would have this content (the double quotes and brackets are required):
["Bhubaneshwar", "Orissa", "India"]
And the code would make use of JSON functions like this:
$json=file_get_contents("city.json");
$x=json_decode($json);
This way you really use standards, and the code is compact.
You could again display the contents of $x like before:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
If you are the creator of that file, and use PHP to create it, then make use of JSON functions as well, as follows:
$x = array("Bhubaneshwar", "Orissa", "India");
file_put_contents ("city.json", json_encode($x));
Related
I am trying to get all the texts not any attributes from HTML tags from a webpage using a search term and then trying to replace them with some other text. My regular expression $pattern1 = "/>([^<]*)</g" for this which gets the text from the tags. Though it isn't working here but it works here https://regex101.com/r/bExomf/2
Even if it works, I am having a problem integrating it with the search term like $pattern variable.
Here below is the code:
<?php
$file = 'j2-regex.html';
$searchfor = 'J2';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
$pattern1 = ">[^<]*</g";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
// Old string
$str_old = $searchfor;
// New string
$str_new = "J<sup>2</sup>";
// Replacing part of string
$final_str = str_ireplace($str_old,$str_new,$contents);
echo("Modified String : ");
echo($final_str);
}
else{
echo "No matches found";
}
Maybe this helps a bit, if you really have to use regex.
<?php
$file = 'j2-regex.html';
$searchfor = 'J2';
$str_new = "J<sup>2</sup>";
$regex = "/<.*?>(*SKIP)(*FAIL)|" . $searchfor . "/";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
$final_str = preg_replace($regex, $str_new, $contents);
echo("Modified String : ");
echo($final_str);
This is the working code:
<?php
$file = '../j2-regex.html';
$searchfor = $_POST['searchTerm'];
$replaceTerm = $_POST['replaceTerm'];
$regex = "~<.*?>(*SKIP)(*FAIL)|" . $searchfor . "~";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
if(preg_match_all($regex, $contents)){
echo $msg = "Matches Founded & File Replaced <a class='btn btn-success' target='_blank' href='j2-regex.html' style='float: right;bottom: 9px;position: relative;'>Visit Webpage</a>";
// // Replacing part of string
$final_str = preg_replace($regex, $replaceTerm, $contents);
// echo("Modified String : ");
// echo($final_str);
$myfile = fopen("../j2-regex.html", "w") or die("Unable to open file!");
fwrite($myfile, $final_str);
fclose($myfile);
// file_put_contents($file , $final_str, FILE_APPEND | LOCK_EX);
}
else{
echo $msg = "No Matches Founded <a class='btn btn-success' target='_blank' href='j2-regex.html' style='float: right;bottom: 9px;position: relative;'>Visit Webpage</a>";
}
?>
Hello i have a script php and javascript, i want call my function javascript from php, but i have a problem when my string have a new line, when i turn firebug in firefox
this error is
"SyntaxError: unterminated string literal"
This is my code
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data =nl2br("hello \n world");
echo 'Click';
?>
Help Me, Thank's
Fixed
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data = str_replace("\n", '\n', "hello \n world");
$data = preg_replace( "/\r|\n/", "", $data);
echo 'Click';
?>
Add an additional treatment to your string to remove line breaks :
$data = nl2br("hello \n world");
$data = preg_replace( "/\r|\n/", "", $data );
Then echo
echo '';
instead of
echo '';
Add and escape simple quotes between the variable for javascript ton consider it a string
concat your var to the outputed string because between simple quotes, it will not be interpreted (on the contrary of double quotes).
Then if you just want to add a line break directly in the alert, you should just do the following :
$data = "hello \\nworld";
echo 'Click';
If you want to display HTML into an alert box, consider using a popin javascript plugin.
As mentioned in the comments, single quotes will not interpret variables. You need to switch your quote types around, and add quotes around the data variable:
echo "";
I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?
i have the following code, but it will not work. i am trying to create a script output:
echo "<script type=\"text/javascript\"><!--\n";
echo "SLIDES = new slideshow(\"SLIDES\")\n";
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname ) {
echo 's = new slide()\n';
echo 's.src = \"http://cashbackflorida.com/wpradmin/modules/wprrets/photos/'.$result ->MLS.'/'{$fname}\n\"';
echo 's.width = \"560\"\n';
echo 's.height = \"420\"\n';
echo 's.alt = \"{$fname}\"\n';
echo 's.text = unescape(\"\")\n';
echo 's.link = \"\"\n';
echo 's.target = \"\"\n';
echo 's.attr = \"\"\n';
echo 's.filter = \"\"\n';
echo 'SLIDES.add_slide(s)\n';
}
echo '--></script>\n';
Don't do it this way. Just output the array to JavaScript and deal with it there.
var files = <?php echo json_encode($files); ?>;
You'll find the problem in your string escaping
echo 's.height = \"420\"\n';
You can't escape in single quote strings like that. So try this
echo "s.height = \"420\"\n";
You do NOT need to escape single quotes within double quotes or visa versa, but you can only get a newline character like that in a double quote string.
I would recommend HEREDOC for this kind of string writing though.
$fnamej = json_encode($fname);
echo << EOT
s.height = "420";
s.alt = $fnamej;
EOT;
I am also inclined to say that you'd be better off handling this in javascript. This may end up behaving very badly all of a sudden, and it will take up more bandwidth.
<?php
include_once("database.php");
Header("content-type: application/x-javascript");
if(isset($_GET["files"])){
$src = explode("+",$src);
for($i = 0;$i<=count($src);$i++){
echo "console.log('$src');";
echo "console.log('$src[$i]');";
$file = preg_replace('#[^a-z0-9]#','',$src[$i]);
echo "console.log('You\'ve select $file');";
}
exit();
}else{
echo "console.error('No Files were found. Please try again, make sure your request is correct')";
}
?>
I'm trying to create a dynamic JavaScript file, and the consoles are working but my iteration of the $src is not working.
EX:
$_GET["files"] ===> file1+file2+file3+file4
url looks like myfile.php?files=file1+file2+file3+file4
So basically I want to split these up into an array by seperating the + in the $_GET I'm new to PHP and I'm trying to learn this on my own but there is not clear cut documentation that I can find quickly.
ALSO
Am I do my preg_replace correctly? I want to ensure there is no malicious injection going on
UPDATE
if(isset($_GET["files"])){
$src = explode("+",$_GET["files"]);
foreach($src as $files){
$file = preg_replace('#[^a-z0-9]#','',$files);
echo "console.log('$file');";
}
exit();
}
//Direct Output:
==>You've Selected aweelemtawe
//Output should be:
==>You've Selected awc
==>You've Selected elemt
==>You've Selected awe
For the incorrect usage of explode()
The following line contains your explode() call
$src = explode("+",$src);
At this stage (using the code example you've posted above) $src will not contain any data to be explode()ed. You want to use the $_GET['files'] value as the parameter
$src = explode("+", $_GET['files']);
See the php docs on explode for more info on how it works.
For your looping/iteration
For your loop you may also want to change your loop to check for $i < count($src). If you have file1+file2+file3+file4 the array will have 4 items at index 0, 1, 2 and 3. You want that statement to read $i < 4 not $i <= 4.
However... as #TML suggested, using foreach is preferred over for when directly iterating over an array.
foreach(explode('+', $_GET['files']) as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
For the sake of simplifying the example, the above is essentially equivalent to
$src = explode('+', $_GET['files']);
foreach($src as $file)
{
// work with $file here (each one will be an element of the exploded array)
}