How to get first word of URL parameter - php

I want to echo only the first word of a url parameter. For example: /?name=Mike%20Jackson. I want only "Mike". How is that done?
I can get the whole parameter.
<?php // show welcome back message if coming from the waiting list email
$name = '';
if (isset($_GET["name"]))
{
$fullname = $_GET["name"];
}
?>
I expect the first word only.

To break the string at a space, you would use the explode function. That separates the parameter and breaks it into an array, so to get the first word you just need to get the 0th index:
$fullname = explode(" ", $_GET["name"])[0];
If space in your URL is encoded as in your example, you just need to replace the space with the encoding:
$fullname = explode("%20", $_GET["name"])[0];
Edit: As pointed out in the comments, the first method should be the way to go because your method of getting the parameter automatically decodes the URL.

Related

Receive JSON POST in PHP with ENTER in one of the field value

When "descriptions" field has "enter" (newline) API is failing.
Image to check all parameter sent by users
Below code to get the data from posted JSON.
// get posted data
$jason_value = json_decode(file_get_contents("php://input"));
$crm_id = $jason_value->data->crmId;
$descriptions = $jason_value->data->descriptions;
I would like to accept descriptions as a string one line.
descriptions = "10+ windows modern style 7057655959".
I do not have access to the program where the user enters the description where I can add validation and convert it to \n.
Getting below string after conversion
{ "jwt": "eyJ0", "data": { "crmId": "15876047", "geoconceptAppointmentId": "15876","geoconceptCustomerId": "15876047","status": "Rejected","appointmentDateTime": "","firstName": "Nick Test","lastName": "PA","address": "9112 RUE Tom","city": "MONTREAL","state": "QC","zip": "H2N1T1","country": "CAN","phoneNumber1": "5148332222","phoneNumber2": "5148332222","email": "nbskgg#gmail.com","dateEntry": "2019-06-20 12:02","dateModify": "2019-06-20 12:02","preferredWayToContact": "","textMsgFlag": "Y","hearAboutUs": "Referral","perferredTime": "Anytime","descriptions": "I have to call at 5" pm. ","worklog": "This is the comment ","rejectReason": "Area | Region","referredByDC": "09999","referredByStoreUsername": "store215","assignedUsername": "","createdByUsername": "np","modifiedByUsername": "np","btgMarket": "Montreal"}}
You're correct that in PHP7+, a literal tab or newline is going to cause the json parsing to fail. file_get_contents("php://input") returns a single string so I see no reason why you couldn't just filter that before you attempt to parse it. But maybe I'm missing something.
//Catch Unix OR DOS line endings, but not both
$filter = Array("\n","\n\r");
$replace = " ";
$cleanJSON = str_replace($filter, $replace, file_get_contents("php://input");
$data = json_decode($cleanJSON));
I want to point out that after this point, your code is referencing a variable that does not exist: $jason_value
$crm_id = $jason_value->data->crmId;
$descriptions = $jason_value->data->descriptions;
To reference properties of the object you just created, go directly to $data:
$crm_id = $data->crmId;
$descriptions = $data->descriptions;
I expect that you'd want to replace the newline with a space but you may just want an empty string if what you're actually encountering has a space before the newline but that's impossible to tell from what we have.

parse non encoded url

there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.

Create URL with only A-Z characters that includes variable and extension

I am trying to create file links based a variable which has a "prefix" and an extension at the end.
Here's what I have:
$url = "http://www.example.com/mods/" . ereg("^[A-Za-z_\-]+$", $title) . ".php";
Example output of what I wish to have outputted (assuming $title = testing;):
http://www.example.com/mods/testing.php
What it currently outputs:
http://www.example.com/mods/.php
Thanks in advance!
Perhaps this is what you need:
$title = "testing";
if(preg_match("/^[A-Za-z_\-]+$/", $title, $match)){
$url = "http://www.example.com/mods/".$match[0].".php";
}
else{
// Think of something to do here...
}
Now $url is http://www.example.com/mods/testing.php.
Do you want to keep letters and remove all other chars in the URL?
In this case the following should work:
$title = ...
$fixedtitle=preg_replace("/[^A-Za-z_-]/", "", $title);
$url = "http://www.example.com/mods/".$fixedtitle.".php";
the inverted character class will remove everything you do not want.
OK first it's important for you to realize that ereg() is deprecated and will eventually not be available as a command for php, so to prevent an error down the road you should use preg_match instead.
Secondly, both ereg() and preg_match output the status of the match, not the match itself. So
ereg("^[A-Za-z_\-]+$", $title)
will output an integer equal to the length of the string in $title, 0 if there's no match and 1 if there's a match but you didn't pass it another variable to store the matches in.
I'm not sure why it's displaying
http://www.example.com/mods/.php
It should actually be outputting
http://www.example.com/mods/1.php
if everything was working correctly. So there is something going on there, and it's definitely not doing what you want it to. You need to pass another variable to the function that will store all the matches found. If the match is successful (which you can check using the return value of the function) then that variable will be an array of all matches.
Note that with preg_match by default only the first match will be returned. but it will still generate an array (which can be used to get isolated portions of the match) whereas preg_match_all will match multiple things.
See http://www.php.net/manual/en/function.preg-match.php for more details.
Your regex looks more or less correct
So the proper code should look something like:
$title = 'testing'; //making sure that $title is what we think it is
if (preg_match('/^[A-Za-z_\-]+$/',$title,$matches)) {
$url = "http://www.example.com/mods/" . $matches[0] . ".php";
} else {
//match failed, put error code in here
}

Stripping text from url

Im trying to strip find_loc= and &cflt=pizza I got the majority stripped its just these last 2 things and whenever I try to use trim it doesn't delete it out it keeps saying array even when i try to print it, it says array.
<?php
$foo = 'http://www.yelp.com/search?find_loc=2190+W+Washington+Blvd%2C+Los+Angeles+90018&cflt=pizza ';
$blah = parse_url($foo);
$blah[query];
//the code above echos out find_loc=2190+W+Washington+Blvd%2C+Los+Angeles+90018&cflt=pizza
$thids = trim(''.$blah.'','find_loc=');
echo $thids;
?>
$thids = str_replace(array('&cflt=pizza','find_loc='), '', $blah);
parse_str($blah['query'], $query_vars); // decompose query string into components
unset($query_vars['find_loc']); // delete this particular query variable/value
unset($query_vars['cflt']);
$blah['query'] = http_build_query($query_vars); // rebuild the query string
$foo = http_build_url($blah); // rebuild the url

Isolate part of url with php and then print it in html element

I am building a gallery in WordPress and I'm trying to grab a specific part of my URL to echo into the id of a div.
This is my URL:
http://www.url.com/gallery/truck-gallery-1
I want to isolate the id of the gallery which will always be a number(in this case its 1). Then I would like to have a way to print it somewhere, maybe in the form of a function.
You should better use $_SERVER['REQUEST_URI']. Since it is the last string in your URL, you can use the following function:
function getIdFromUrl($url) {
return str_replace('/', '', array_pop(explode('-', $url)));
}
#Kristian 's solution will only return numbers from 0-9, but this function will return the id with any length given, as long as your ID is separated with a - sign and the last element.
So, when you call
echo getIdFromUrl($_SERVER['REQUEST_URI']);
it will echo, in your case, 1.
If the ID will not always be the same number of digits (if you have any ID's greater than 9) then you'll need something robust like preg_match() or using string functions to trim off everything prior to the last "-" character. I would probably do:
<?php
$parts = parse_url($_SERVER['REQUEST_URI']);
if (preg_match("/truck-gallery-(\d+)/", $parts['path'], $match)) {
$id = $match[1];
} else {
// no ID found! Error handling or recovery here.
}
?>
Use the $_SERVER['REQUEST_URI'] variable to get the path (Note that this is not the same as the host variable, which returns something like http://www.yoursite.com).
Then break that up into a string and return the final character.
$path = $_SERVER['REQUEST_URI'];
$ID = $path[strlen($path)-1];
Of course you can do other types of string manipulation to get the final character of a string. But this works.

Categories