Replace % with - in url PHP - php

Ok i have one maybe stupid question
On my website i have search options, that is input with GET metod, but when someone enter long seperated word like
I AM SOMETIMES BLANK
i got this in my url
http://www.example.com/search.php?page=1&txtPretraga=I%AM%SOMETIMES%BLANK
I dont know how to change that?
I want clean URL like this
http://www.example.com/search.php?page=1&txtPretraga=I-AM-SOMETIMES-BLANK
I want to change % with - in my ULR
Any ideas?

You can use str_replace in your php code:
http://php.net/manual/en/function.str-replace.php
$search_qry = "Whatever%They%Type";
$replace = str_replace($search_qry, "%", "-");
EDIT:
In the case of your strings - they have spaces, which show up as % in a URL, so use this before you do your $_GET
$search_qry = "Whatever They Type";
$replace = str_replace($search_qry, " ", "-");
EDIT 2
Since this is a $_GET - Javascript will have to be used to clean the string before it's sent. (using jQuery and javascript here)
<script type = "text/javascript">
$(document).ready(function(){
$('.example-input').blur(function(){
var str = $(this).val();
var clean_str = str.replace(" ", "-");
$(this).val(clean_str);
});
});
</script>
This should clean the string in the input box before it's even sent through the get.
or instead of .blur, you can use $('submit-button').click(function(){...
Or, you can use the .htaccess file to do a mod rewrite. But I don't know that well enough.

Ok, i got the fix for the problem :)
This is not question for PHP, it is for Javascript and i wrote this function
<script type="text/javascript">
function provera() {
var x=document.forms["hsearch"]["txtPretraga"].value;
var n=str.replace(" ","-");
}
</script>

Related

How to get html ID passed in URL in PHP [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP?     => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
                                    YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..

How can get string after "#" from url using php? [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP?     => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
                                    YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..

Replace special characters with alphabet in jQuery

How to remove Special Character and alphabet from variable by jQuery.
I have
var test = +985
But I want to get value as
var another = 985
It should not allow character as well + as I am using it in Phone Code
try to something like this...
var inputString = "~!##$%^&*()_+=`{}[]|\:;'<>,./?Some actual text to keep, maybe...",
var outputString = inputString.replace(/([~!##$%^&*()_+=`{}\[\]\|\\:;'<>,.\/? ])+/g, '-').replace(/^(-)+|(-)+$/g,'');
Might be duplicate of this
You just need to use replace function it's first parameter is symbol you want to replace and another is symbol or word you want to replace with.
For more info please visit Javascript replace function
var test = "+985";
var another = test.replace("+", "");
Try this to extract number:
var test = +985;
alert(test+"".match(/\d+/));

Jquery set PHP $_GET array

Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Send Get with jQuery with spaces

I have a problem with a word count using the jQuery. The method is working as soon as I click space it will stop.
HTML:
<textarea id="essay_content_area" name="essay_content" onkeydown="words();"></textarea>
<td>Number of words: <div id="othman"></div></td>
jQuery:
function words(content)
{
var f = $("#essay_content_area").val()
$('#othman').load('wordcount.php?content='+f);
}
PHP file:
if(isset($_GET['content']))
{
echo $_GET['content']; // if it works I will send this variable to a function to calculate the words
}
the script shows the content until I click space. any suggestions ?
You need to url-encode the value before sending it over to your PHP script as the value of a GET parameter. Consider this:
function words(content)
{
var f = $("#essay_content_area").val()
$('#othman').load('wordcount.php?content=' + encodeURIComponent(f));
}
You don't need php to count the words you can use JS, something like this:
function words(content)
{
// Get number of words.
var words = content.split(" ").length;
}
You need to url encode your variable before you send it (space is not a valid url character):
function words(content)
{
var f = encodeURIComponent($("#essay_content_area").val());
$('#othman').load('wordcount.php?content='+f);
}

Categories