How To Remove Query String Using Regular Expressions

free web hosting
Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

How To Remove Query String Using Regular Expressions

TavoxPeru
Hi,

I'm a complete newbie using regular expressions and what i want to do is to remove all the parameters of the query string of any url using regular expressions, how can i do this?

For example if i have some urls like these:

http://www.domain.com/file1.php?var1=value1&var2=value2
http://www.domain.com/file2.php?var1=value1&var2=value2
http://www.domain.com/file3.php?var1=value1&var2=value2

I want to only get these ones:

http://www.domain.com/file1.php
http://www.domain.com/file2.php
http://www.domain.com/file3.php

If it is possible please post not only the php code also the perl and posix syntax.

Best regards,

 

 

 


Reply

vujsa
Well, it may not be the most efficient method but I did write the following for Perl Compatable:
CODE
<?php
$string = "http://www.domain.com/file1.php?var1=value1&var2=value2";

$search = '|(\.php)(.*)|i';
$replace = '${1}';

echo preg_replace( $search, $replace, $string );

?>


There may be a better way to do this but this is how I usually do it.

Here is the same code for POSIX Extended:
CODE
<?php
$string = "http://www.domain.com/file1.php?var1=value1&var2=value2";

$search = '(\.php)(.*)';
$replace = '\\1';

echo ereg_replace( $search, $replace, $string );

?>


The "p" in preg_replace is for Perl while the "e" in ereg_replace is for POSIX Extended.

I'll attempt to expalin each individually,

preg_replace()
This function requires 3 parameters; a search string, a replace string, and a base string.
As a result , I named my variables, $search, $replace, and $string.
Of course, you do not have to use variables, you can direct insert the strings in the function.

I find it easier to explain and use the function with the variables and I'll explain them now.
The $search variable contains the regular expression string. This will vary greatly depending on what you want to find, how you want to use it later, and how simple the base string is.
First, use single quotes, double quotes have their use but not here!
The pipe character '|' is used a delimiter, it tell the function when the regular expression starts and stops since additional information is contained in the string as well.
The next thing I do is use an opening parenthesis '(' which specifies the beginning of a group. It isn't essntial in this example, but is useful later.
now, the period in regular expressions has it's own use so to match an actual period, you have to escape it with a backslash '\' which is universally used in programming to escape a character. so '\.php' means match '.php' followed by a closing parenthesis ')' to end the group.
The next thing is to match pretty much everything else! (.*) means just that take everything and put it ina a group. the period as suggested has it's own use and here it says, any character and the asterisks '*' means zero or more matches of that character. It will keep matching every character until it matches the next regex pattern in the search string. In this case, there isn't another regex so it will finish off the entire base string matching every character.
Then we finish the regex portion of the string and follow it with the ending delimiter (pipe). After the ending delimiter, there is an 'i'. This means that the regex is case insensitive! To make it case sensitive, leave the 'i' out.
So, '|(\.php)(.*)|i' means match the groups of characters that matches '.php' followed by the group of any characters till the end of the string without consideration of case.

The replace string is simple enought to explain, ${1} simple means use whatever the first group that was matched as the replacement. In this case, it means '.php'.
The same can be accomplished with '\\1'. This is called a backe reference. It is most handy when you want to simple extract something from a string instead of replace it. It is also how you turn query string url's into search engine friendly url's. Another use is for referal links. If a person visits your website from a search engine, you can extract the exact search term they used to find you!

ereg_replace()
This function is exactly the same except it doesn't require a delimiter since there are no further parameters used in this function. It also will not allow the replace parameter to use the '${1}' of back reference. Only the '\\1' method is allowed!

The PHP manual recommends using the Perl compatable functions since they are more efficient and offer more flexibility.

I'm not sure that I have expalined everything well enough but I'll try to clear some things up here:
The delimiter in preg_replace can be nearly any character as long as the character isn't used in the search pattern. (|,@,#,%, {},[],<>,/)

The reason you might use the back reference is because you might match multiple patterns like so:
'#(\.php|\.asp)(.*)#i' Will strip out the query data from PHP and ASP links. Notice that I changed the delimiters to pound '#' instead of pipe since the pipe is used in the regex to denote 'or'. Now if the link is to an ASP file, with the back reference, the file extension will be correct in the output!
So:
www.domain.com/file1.php?var1=value1&var2=value2 will become www.domain.com/file1.php
www.domain.com/file2.asp?var1=value1&var2=value2 will become www.domain.com/file2.asp

Now, just to leave you with one last thought, here is the most simplified version of the script and means replace everything from the question mark '?' to the end with nothing:
CODE
<?php
$string = "http://www.domain.com/file1.asp?var1=value1&var2=value2";

$search = '#\?.*#';
$replace = '';

echo preg_replace( $search, $replace, $string );

?>

Since it already looks for any character, no modifier is needed after the delimiter. Also, since the match begins after the file extention, it will be left alone.

Here is the same for POSIX Extention:
CODE
<?php
$string = "http://www.domain.com/file1.asp?var1=value1&var2=value2";

$search = '\?.*';
$replace = '';

echo ereg_replace( $search, $replace, $string );

?>


I thought I should provide you with a more complex methed first to show you what was going on! The more options (complex) the regex, the more powerful it will be but also require more resources to execute. It all depends on your needs.


There are a few regex topics on the forums that will help.

Hope this helps. cool.gif

vujsa

 

 

 


Reply

TavoxPeru
Thanks a lot, your examples helps me to resolve my problem.

Best regards,

Reply

cryptwizard
It's pretty simple, for faster speeds you don't even need regex.
Just use:
CODE
$original_url = 'http://www.domain.com/file1.php?var1=value1&var2=value2';
$split_url = explode('?', $original_url);
$no_querystring_url = $split_url[0]; // http://www.domain.com/file1.php

It might take more lines of code, but it is executed much faster than regex.

Reply

TavoxPeru
QUOTE(cryptwizard @ Apr 28 2007, 06:12 AM) *
It's pretty simple, for faster speeds you don't even need regex.
Just use:
CODE
$original_url = 'http://www.domain.com/file1.php?var1=value1&var2=value2';
$split_url = explode('?', $original_url);
$no_querystring_url = $split_url[0]; // http://www.domain.com/file1.php

It might take more lines of code, but it is executed much faster than regex.

Thanks, i will try it and check if it is executed much faster than the previous solution posted.

Best regards,

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. php regex pound - 160.46 hr back. (1)
Similar Topics

Keywords : remove, query, string, regular, expressions

  1. Remove Windows Update Uninstall Information
    Sick of seeing $NtUninstall in Windows Folder, I am! (4)
  2. Regular Expressions
    (6)
    In PHP and many other programming languages, I have heard of this powerful syntax called RegEx, or
    regular expressions. It allows you to find strings that match a certain pattern. I had to use a
    regex expression to search for a specific string of text within a block of text once, and someone
    told me to use a regular expression. The example that they wrote worked, although it was extremely
    confusing and I didn't know what it meant. http://www.regular-expressions.info/ gives a great
    tutorial on regular expressions, the syntax and stuff. I'm not sure if this is ....
  3. Can't Make This Query Working.
    (2)
    Hi again. I am trying to make a new Register script. But now, there is only one thing that is not
    working.. I can't make the following query work. CODE mysql_query("INSERT INTO
    members(username, password, email, register_date) VALUES
    ('$user','$pass','$email',
    '$reg_date')") or die("Failed to register.<br>
    Error:".mysql_error()); this is the current date variable, that is causing
    the error. (if I remove it from the query, it works just fi....
  4. Using Regular Expressions To Parse Functions
    (5)
    I have a hierarchy of functions represented as something like:-
    @BeforeText(@AfterText(@ReadURL('http://www.quotationspage.com/quote/1.html')@,'
    ',True)@,' ',True)@ Each of the functions follow the format @FunctionName( )@. The
    ParamString itself can be composed of a string, a number or a boolean value. For example:-
    @AfterText('String', "st", True)@ - This function returns the portion of text following the
    specified substring. It is composed of three parameters. First one is the string being worked on,
    second is the substring being sou....
  5. Using Regedit To Remove Viruses
    How to remove specific viruses using regedit (8)
    How to remove particular type of viruses from your system? Will using Regedit help???If so how to do
    it using regedit?For instance my system is affected by NTdetect virus so what should i do to remove
    it??? ....
  6. Regular Expressions Not Matching
    (4)
    Hi All, I am using Regular Expressions in VB.NET to find illegal filename characters in a string.
    The user enters and name, and it then saves the file with that name. I just need to make sure that
    the filename doesn't contain illegal filename characters. The characters are / \ : ?
    " | (is there any others?) I am using the following regex at the moment, but it doesn't
    seem to be picking up backslashes. CODE Dim myRegex As New
    System.Text.RegularExpressions.Regex("[\/:?'=<>|]")
    Every other charact....
  7. Making A Link = Mysql_query
    (8)
    Hey! I will try to make this as clear as possible. how can I make the following. I have a
    list, of all members on my site. If I press on a members name(link), I will come to his profile. To
    come to his profile, I need to get out some vaule from the database, but to get out some value from
    the database, I must tell the code, how it should know who the user is (hard to understand?). To do
    that, I must add a mysql_query in the code ( I think), like "SELECT user FROM dbname WHERE
    user=link".. This is just how I think it works. I know it is kinda wrong.. but I don'....
  8. Filtering Out Unwanted Junk Mail Using Regular Expression.
    Use this Regular Expression with the cPanel email filter to limit your (0)
    I'm so irritated with the amount of spam I get on the email accounts I have hosted at AstaHost.
    It isn't the servers fault that I get so much junk mail! It wouldn't be so bad but my
    junk mail filter on my home system doesn't scan IMAP accounts which I use since my email client
    won't separate POP3 accounts properly. So I finally got to the point I had to do
    something! I'm getting about 25 junk mail messages a day spread over 5 different email
    accounts. If I go a few days without checking my email, I have a lot of work to do to clean ....
  9. String Theory
    (9)
    I've heard of string theory, and I know that it's baisically the belief that multiple
    universes exist in parallell and only gravitons can travel between them. My question is: Do you
    believe in String Theroy, and what do you know about it that you could teach me?....
  10. Strange Ascii Code 22 Character Detected In Connection String
    (9)
    Warning: Unexpected character in input: '' (ASCII=22) state=1 in
    /usr/local/cpanel/cgi-sys/php4 on line 928 Parse error: syntax error, unexpected T_STRING in
    /usr/local/cpanel/cgi-sys/php4 on line 928 i get that when i get on to my site:
    http://eggie.sphosting.com how to solve it?....
  11. Mysql Query Question
    MySQL Select query problem (3)
    Hii Guyz, I am having this little problem creating a query in MySQL. Problem description: Table:
    mytable Table Structure: IssueId | ToolName | Status 01 | Tool1 | Open 02 | Tool1 | Closed 03 |
    Tool2 | Closed 04 | Tool3 | Open Now, I want to get the results in the following form: ToolName |
    Count(Open) | Count(Closed) For the above input, result will be: Tool1 | 1 | 1 Tool2 | 0 | 1 Tool3
    | 1 | 0 There should be NO duplicate toolName in output. Thnaks, Manu.....
  12. Safari Island De Luxe : Where Are The High Scores ?
    Would like to remove them, no way ! (0)
    Hi, all ! where are the hiscores in Safari Island de Luxe (Gamehouse) ? I cannot reach again my
    past hiscores, so I would like to erase the hiscores, no way ! I tried de-installing the game
    and re-installing it, the old socres are still there. Tried to also removed the gamhouse things in
    the windows registry during advanced de-install, the old hi-scores are still there. They are not in
    a file in "my documents" either, where are they hidden ? Did someone already have this problem ? How
    did you solve it ? Regards Yordan....
  13. Afs Adapter Problem
    How do I remove it? (4)
    Ok, I am currently using Windows Vista ultimate, and for a while I was using OpenAFS. Well the
    problem happened that it added an adapter to my list of network adapters that is called
    'AFS' Now this would be ok, but I would like to remove it to speed up my system a little, as
    I am no longer using OpenAFS, and have since removed it... However, when I go to network
    connections, and i try and delete it. It asks if I would like to delete it, and I click ok, and then
    i get 'error deleting connection, the selected connection cannot be deleted' Now this
    connect....
  14. Check For Occurence Of Substring In String
    (3)
    Hi, I've been working on a personal messenger, and one of the main problems I'm having is
    that if there are 10 or so replies to a message, you end up with a subject like this: Re: Re: Re:
    Re: Re: Re: Re: ..... etc. you get the picture Is there a function on PHP to check for an occurence
    of a substring in a string? So I could check if the subject already has a "Re: " in it? It would be
    really helpful, thanks!....
  15. The Absolute Bare Minimum Every Programmer Should Know About Regular Expressions
    (1)
    Well, the title says it all and I really don't have anything to add to that, except to say that
    this is a really, really powerful technology that is very pervasive in many programming as well as
    scripting languages and as well in mainstream database products. I really recommend you put in the
    time and effort to learn regular expressions, they are power tools that are going to open for you a
    whole new world of text processing possibilities. Link:
    http://immike.net/blog/2007/04/06/the-abso...ar-expressions/ ....
  16. Php Any Variable In String.
    (1)
    OK well I am making a new php program and I am trying to add bbcode to it. Anyway I was going to
    replace each thing by it self, but that could cause errors. Anyway is there a way to make a variable
    be anything? Here is an example: CODE This is the bbcode:
    [color=00FF00]Hey[/color] In my php: $bbcode =
    array("[color=".$a."]"); $html = array( "<font
    color='#".$a."'>"); $topic_content =
    str_replace($bbcode, $html, $posted_bbcode)....
  17. Problem With Form Elements
    How to Add/Remove form elements created dynamically (3)
    Hi everybody, i have a problem with a form where i want to add or remove elements from it
    dynamically, i'm working on an invoice form, like the following: CODE <form
    name="a" > <table id="header_data"> <tr>    <td
    width="20%">Nro.</td><td ><input type="text"
    size="20" value="val_1"></td> </tr> <tr>    <td
    width="20%">Date</td><td ><input type="text"
    size="20" value="val_2"&#....
  18. [help] Vista - Remove White Selection Highlight From Icons
    (11)
    I just installed Vista for a friend and took the opportunity to play around with it a little. I came
    across a rather annoying problem i cant resolve currently. The icons on the desktop (Folders or
    applications icons), when hovered upon shows a white highlight box. When the icon is selected the
    highlight stays. This white box is pretty annoying and if i dont want that to appear, what should i
    do. Just like the icons in XP without any border. I searched online and i found this one solution
    but i dont know how to reach "Display Properties" or "Customize Desktop and Web" o....
  19. Help Spliting A String Into 3 Variables In C++
    I have searched on the net but havent found much help (2)
    Hi there im new around here ^^, my original language is spanish so sorry for any wrong word i
    use,... Im working on some features for my program to load a Favorite games list from a text file
    but the problem I have is not parsing the file, is processing a string and spliting it into 3
    variables, then I will use them to insert as items in a List View control, I just dont know what is
    wrong in the following code... CODE
    //------------------------------------------------------------             TCHAR* pszRomname =
    NULL;         TCHAR* pszTitle= NULL;         TCHAR* p....
  20. Php String To Int Typecasting
    (5)
    I've been working on writing this program that needs strings to be converted to integers.
    Sometimes PHP works by doing the converting for me, but sometimes it just breaks down and quits
    working. I've got no idea why. $sub1 = 0+substr($text, 0, 3); $sub2 =
    0+substr($text, 3, 6); $sub3 = 0+substr($text, 6, 9); $sum =
    0+$sub1+$sub2+$sub3; echo $sum; Basically, $text is a string of numbers
    that looks something like: 296294255268313 and so on. Then I use substr to get the first three
    digits/letters of �....
  21. Remove Sound From Avi
    (10)
    i downloaded a movie and now there is a voice over the movie and i wanted to remove it but i do not
    even have a clue where to start. so any help will be great Thanks....
  22. Apache Query: Requirements To Run Own Web-Server?
    (9)
    Hi friends, I have learnt that one can host own website using apache web server. Does that mean
    that I will have to keep my computer ON all the time. What about browsing? How will people visit my
    website. I mean what address will they have to put in the address bar of browser where currently I
    am putting the address of my website. And what all security policies will I need to apply to prevent
    my computer being hacked. I was just browsing internet when I came to know that a windows based
    machine gets hacked in 2 days and a Linux based machine in 4 days on average. If th....
  23. Meebo: Yahoo Messenger Alternative
    one query too (8)
    hi all, There is an alternative of yahoo messenger available on internet. Its a website. They
    transfer data from port number 80. If your network administrator has blocked yahoo messenger then
    you can chat with your friends through this website. The only disadvantage is that you can't do
    voice chat or more advanced things you do in messenger. The website is: CODE
    http://www35.meebo.com Its still in alpha stage. But it can also log in to MSN, AOL, GTalk.
    I have one query regarding this website. What does www35 mean? I have searched on google but i
    couldn&#....
  24. VB6-MS Access Question
    help please (8)
    hi guys, I am developing an application in Visual Basic 6.0 and using MS Access as my backend. What
    i want is that my database should not open when someone doublec clicks on the .mdb file. But my
    application should be able to access it. What can be a possible solution to this problem? Please
    help. Thanx in advance.....
  25. Need Help - How To Remove Session ID From URL
    (6)
    Oflate I was going through Google information for webmasters and I noticed the following technical
    guideline for the webmasters: QUOTE Allow search bots to crawl your sites without session IDs or
    arguments that track their path through the site. These techniques are useful for tracking
    individual user behavior, but the access pattern of bots is entirely different. Using these
    techniques may result in incomplete indexing of your site, as bots may not be able to eliminate URLs
    that look different but actually point to the same page. It clearly shows that undesir....
  26. Airtel GPRS
    Information about my not so regular Internet connection. (22)
    I use a SAMSUNG SGH-C200N handset coupled with Airtel (a GSM Service Provider in Asia) GPRS to
    connect to the internet. Here is a review about my Internet Connection - Points > By default
    Windows always shows the connection speed to an outstanding 115.6 KBps. Although, from what I have
    seen via the connection status, when downloading files from a good server, the maximum speed that I
    get is around 5 Kbps. During the peak hours, the connection's speed deteriorates and the data
    transmission becomes intermittent. Every Page (except for good ol' Google)....
  27. Remove Window Animation - Make It Run Faster
    (8)
    make your computer run a little faster. You can shut off the animation displayed when you minimize
    and maximize Windows. 1. Open RegEdit 2. Go to HKEY_CURRENT_USER\Control panel
    \Desktop\WindowMetrics 3. Create a new string value "MinAnimate". 4. Set the value data of
    0 for Off or 1 for On this should put less stress on your graphics card if you have an older
    computer.....
  28. Remove Msn Messenger In Windows Xp
    For XP user only (10)
    How do you remove MSN Messenger in Windows XP? Not from the Add/Remove program list but by locating
    SYSOC.INF in the \Windows\INF folder (hidden file and folder). Open it in Notepad and
    locate the line: msmsgs=msgrocm.dll,OcEntry,msmsgs.inf,hide,7 Remove the word 'hide' from
    the line and save the file. After making the necessary changes, you'll be able to see MSN
    Messenger in the Add/Remove Windows components list. You can then remove it for good.....
  29. Msn Contacts Removal
    i want to remove or erase added contacts (9)
    i want a little help ... please if sombody know how to erease contacts fromm MSN messenger ID, the
    problem i am facing is that my id is so old and so common and many contacts adds me daily, if i
    allow them, they disturb me and if i dont they are goine in block catagory and now i hav eblock list
    full and added contacts list full, polease tell me how can i REmove the conacts or how can i delete
    my contact so that they neither show in block list nor in allow list, i want my id az a new id, is
    their any way.... if so please tell me... i am so much worried will be waiting....
  30. How To Remove Bad Sectors Or Bad Clusters From HDD
    a tutorial for you all (16)
    hi friends, there is small tutorial to remove Bad Sectors from hdd to remove bad sectors you need a
    program named SeaMap now we start Start the SeaMap.exe software Set the option by typing SD and
    then press enter Press 1 then 0 or 1 to select drive Then press 2 and there will be a option (Y/N)
    press n for No Press Esc button one to go back to command line Type FD Type y for yes the Hdd will
    format the whole disk and removes bad sectors and partitions Now the computer has to be restarted,
    Restart your computer Partition your Hdd using fdisk and then format all partitio....

    1. Looking for remove, query, string, regular, expressions

Searching Video's for remove, query, string, regular, expressions
Similar
Remove
Windows
Update
Uninstall
Information
- Sick of
seeing
$NtUnin
stall in
Windows
Folder, I
am!
Regular
Expressions
Can't
Make This
Query
Working.
Using
Regular
Expressions
To Parse
Functions
Using
Regedit To
Remove
Viruses -
How to
remove
specific
viruses
using
regedit
Regular
Expressions
Not Matching
Making A
Link =
Mysql_query
Filtering
Out Unwanted
Junk Mail
Using
Regular
Expression.
- Use this
Regular
Expression
with the
cPanel email
filter to
limit your
String
Theory
Strange
Ascii Code
22 Character
Detected In
Connection
String
Mysql Query
Question -
MySQL Select
query
problem
Safari
Island De
Luxe : Where
Are The High
Scores ? -
Would like
to remove
them, no way
!
Afs Adapter
Problem -
How do I
remove it?
Check For
Occurence Of
Substring In
String
The Absolute
Bare Minimum
Every
Programmer
Should Know
About
Regular
Expressions
Php Any
Variable In
String.
Problem With
Form
Elements -
How to
Add/Remove
form
elements
created
dynamically
[help] Vista
- Remove
White
Selection
Highlight
From Icons
Help
Spliting A
String Into
3 Variables
In C++ - I
have
searched on
the net but
havent found
much help
Php String
To Int
Typecasting
Remove Sound
From Avi
Apache
Query:
Requirements
To Run Own
Web-Server?
Meebo: Yahoo
Messenger
Alternative
- one query
too
VB6-MS
Access
Question -
help please
Need Help -
How To
Remove
Session ID
From URL
Airtel GPRS
-
Information
about my not
so regular
Internet
connection.
Remove
Window
Animation -
Make It Run
Faster
Remove Msn
Messenger In
Windows Xp -
For XP user
only
Msn Contacts
Removal - i
want to
remove or
erase added
contacts
How To
Remove Bad
Sectors Or
Bad Clusters
From HDD - a
tutorial for
you all
advertisement




How To Remove Query String Using Regular Expressions



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE