Php replace in string - php

I've got string based on current url, look like this:
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10
I want to do a pagination. How to replace in this strng page=x, and limit is choosen from dropdown so also limit=x
So I want to change exxample from above to
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=2&limit=25
I just want to make replacement from (page and limit)
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10
to
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=2&limit=25
where page will be variable from loop, and limit will be constant

You can break the string into an array then modify the required values and again create the string.
<?php
$url = "domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10";
$params = explode("?",$url,2);
parse_str($params[1], $url_array);
$url_array['page'] = 2;
$url_array['limit'] = 5;
$newparams = http_build_query($url_array);
$newurl = $params[0]."?".$newparams;
?>

Related

Changing specific text in php

$url = localhost/project/index.php?letter=0&position=0&bypass=1
How to change position=0 to position=1?
The new $url value will be:
$url = localhost/project/index.php?letter=0&position=1&bypass=1
You can use parse-str and parse-url approach with the help of http-build-query,
$url = "localhost/project/index.php?letter=0&position=0&bypass=1";
// fetching query paramters and save it to output variable
parse_str(parse_url($url,PHP_URL_QUERY),$output);
// changing position value
$output["position"] = 1;
// building back query string
$query = http_build_query($output);
// creating final string
echo parse_url($url,PHP_URL_PATH)."?".$query;
Demo
Output:-
localhost/project/index.php?letter=0&position=1&bypass=1
You have to use the str_replace() function to replace a specific text from string.
$url = str_replace('position=0','position=1',$url);

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

Array values not inserting into database separately

I'm not sure exactly how to phrase this so I will show an example. I'm gathering input values in javascript and passing to my php page where I am trying to insert those values in a database.
Instead of inserting separate values it is inserting the entire string.
Part of my javascript below:
var form = document.forms[0];
var txtS = form["bulletlabels"];
var len = txtS.length;
var bulletlabels = "";
for(i=0;i<len;i++) {
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
}
when I do an alert(bulletlabels); I get this:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
On my php page I have:
$bulletlabels = array($_POST['bulletlabels']);
$length = count($bulletlabels);
for ($i = 0; $i < $length; $i++) {
mysqli_query($con,"UPDATE bullets SET bullettitle = '".$bulletlabels[$i]."' WHERE bulletrow = ($i+1)");
}
This inserts the below string into the database on ONE Row which is not the desired effect:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
But here is the key to my confusion - if I manually type the string in, it inserts onto individual database rows as desired.
This inserts values individually as desired when typed manually:
$bulletlabels = array("0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",);
Does NOT work and inserts the full concatenated string:
$bulletlabels = array($_POST['bulletlabels']);
Hope I explained well enough - arrays elude me.
EDIT:
Fix for the trailing comma:
var delim = "";
for(i=0;i<len;i++) {
bulletlabels += delim+[i]+'_'+(txtS[i].value)+'_label';
delim = ",";
}
Reference link for trailing comma fix:
Can you use a trailing comma in a JSON object?
Try changing the following line:
$bulletlabels = array($_POST['bulletlabels']);
to
$bulletlabels = explode(',', $_POST['bulletlabels']);
Also do not add quotes in your javascript:
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
should be
bulletlabels += [i]+'_'+(txtS[i].value)+'_label,';
Explanation:
Currently, $bulletlabels is an array with one element, and this element is the following string: "0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",. However, you want to have an array with several strings. That's why you need to use the explode function to convert it into a proper array.
Note:
Make sure not to include , in the label names, as it will break with this implementation. If you need to be able to use , too, you should use json functions.

Get specific part of a URL value

I used a code to bulk import the envato items,
for example the envato items url is like this :
http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226
How to get only the part "2833226" of this URL with PHP?
I use wordpress and have used custom fields to insert envato item links
for example a custom field (afflink) with value :
http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226
and this code to call the custom field value in the theme
$afflink = get_post_meta($post->ID, "afflink", false);
How to get only the item number?
Use explode to split using / caracter and then get the last element of array:
<?php
$url='http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226';
$y=explode('/',$url);
$affiliateID = end($y);
?>
$pattern = "/\d+$/";
$input = "http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226";
preg_match($pattern, $input, $matches);
//Your ID
$post_id = $matches[0];
Use this :
value = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
$url = 'http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226?r=1';
$urlParts = parse_url($url);
$path = $urlParts['path'];
$pathParts = explode('/',$path);
$item_id = end($pathParts);
The above code will make sure to avoid query string and read only Uri

passing php variables in query strings

I have a number of url's with different query strings such as
view.php?id=5
view.php?id=6
view.php?id=7
on another php page Im using file_get_contents as below:
$page = file_get_contents('view.php?id=5');
$file = 'temp/form.html';
file_put_contents($page, $file);
This of course only writes the first id '5', so how can i retrieve the 'id' variable on this page and write it in my file_get_contents line so I dont have to write out all the id's in seperate lines
thanks
rifki
If I understand correctly, in the situation you demonstrate you could use a for loop or something like that. But that only works if the IDs are numeric and follow each other up.
Example:
for($i = 5; $i <=7; $i++) {
$page = file_get_contents('view.php?id='.$i);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
Updated:
If your ID comes from database you could select all IDs and loop through that.
Eg.
$sql = 'SELECT id FROM tablename;';
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$page = file_get_contents('view.php?id='.$row['id']);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
If those urls are used to browse some pages you can use the $_GET array (Official PHP Manual for the $_GET method).
It simply gets the value of a variable passed via the get method (i.e. page.php?var1=1&var2=2) so, if you need to get the id value for your page the code should be something like this:
$id = $_GET['id'];
$request = 'view.php?id='.$id;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
The first line gets the id passed via url, then the second creates the request string to pass to your file_get_contents function, then the other are like your code.
This is the case if you request the data from inside of such pages, if, for example, you know all of the pages needed then you can use a for clause to solve this problem.
One of the solutions might be:
$first_page = 5;
$last_page = 7;
for ($i = $first_page; $i <= $last_page; $i++) {
$request = 'view.php?id='.$i;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
With this you simply set the first and the last page you want to request, then you use these values to cycle through the pages and then call your function to do your... "stuff" :D
This is a good approach because then you can set in runtime the values for the for statement so you won't have to change that file every time.
However I think that using an identification different from Integers for your pages would be better, like id=home, or something like that.
If you get the id in your query string I mean url, you should write something like this:
$page = file_get_contents('view.php?id='.$_GET['id']);
$file = 'temp/form_'.$_GET['id'].'.html';
file_put_contents($page, $file);
To retrive the variable from a query string use
$_GET['variable_name']
By default, whenever you make a request to the server it is GET method which is called unless you explicitly specify that the form method to be POST.
//variable_name is the name of the variable in the query string

Categories