How to remove all links from a mixed string with php - php

i have a variable in php can be like this : $string = "hello check out this http://xx.xx/xxx & thanks !!";
i want a function to strip that link and remove it from the string, the url can be with WWW. or without it.
also, this variable can contains multiple urls .
Thanks

You could use regular expressions to do it:
$string = preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&##/%?=~_|!:,.;]*[-A-Z0-9+&##/%=~_|]', '', $string);
That will find every instance of a URL in the string and replace it with a blank string.

You can use a regular expression to match and replace all URL formats, as follows:
$string = preg_replace("/(^¦\s)(http:\/\/)?(www\.)?[\.0-9a-zA-Z\-_~]+\.(com¦net¦org¦info¦name¦biz¦.+\.\w\w)((\/)?[0-9a-zA-Z\.\-_~#]+)?\b/ie","",$string);

Related

PHP- Parsing words from a string without spaces?

My webpage has a variable, $currentPage. This is a string of the php token name of the page I'm currently on.
Example: All categories under the user section have names such as:
uAdminNew, uAdminEdit, ect..
I would like for a way to parse out the uAdmin and just determine what is the last word (New and Edit) and call upon functions from there.
I have my navigation system working through these names, therefore I can't change the names or I would to make it easier to parse. Such as adding delimiters.
Is this something only Regex can solve or is there a simpler solution I'm missing? If this is Regex could you explain or provide a link as to how I would go about using it to test against a specific list of strings? I'm very new to it.
For example, so:
$str = 'uAdminEdit';
$ar = preg_match('/([A-Z][^A-Z]+$)/', $str, $m);
echo $m[1]; // Edit
Does the pagename always start with uAdmin? If so, you could split the string by "uAdmin" with explode():
$page = 'uAdminEdit';
echo explode('uAdmin', $page)[1]; //Output: Edit
Or simply remove "uAdmin" with str_replace():
$page = 'uAdminEdit';
echo str_replace('uAdmin', '', $page); //Output: Edit
If you just want the section after uAdmin, use the regex capture groups
preg_match('/uAdmin(.*)/', $sub, $matches);
echo $matches[1]

preg_replace how change part of uri

I am trying to change all the links of a html with php preg_replace.
All the uris have the following form
http://example.com/page/58977?forum=60534#comment-60534
I want to change it to:
http://example.com/60534
which means removing everything after "page" and before "comment-", including these two strings.
I tried the following, but it returns no changes:
$result = preg_replace("/^.page.*.comment-.$/", "", $html);
but it seems that my regex syntax is not correct, as it returns the html unchanged.
Could you please help me with this?
The ^ is an anchor that only matches the start of the string, and $ only matches at the end. In order to match you should not anchor the regular expression:
$result = preg_replace("/page.*?comment-/", "", $html);
Note that this could match things that are not URLs. You may want to be more specific as to what will be replaced, for example you might want to only replace links starting with either http: or https: and that don't contain whitespace.
You probably simply need this: http://php.net/manual/en/function.parse-url.php
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
Alternate way without using regular expression.
Uses parse_url()
<?php
$url = 'http://example.com/page/58977?forum=60534#comment-60534';
$array = parse_url($url);
parse_str($array['query'], $query);
$http = ($array['scheme']) ? $array['scheme'].'://' : NULL;
echo $http.$array['host'].'/'.$query['forum'];
?>
Demo: http://codepad.org/xB3kO588

PHP Regex moving selection to different location in string

I currently have this regex:
$text = preg_replace("#<sup>(?:(?!</?sup).)*$key(?:(?!</?sup).)*<\/sup>#is", '<sup>'.$val.'</sup>', $text);
The objective of the regex is to take <sup>[stuff here]$key[stuff here]</sup> and remove the stuff within the [stuff here] locations.
What I actually would like to do, is not remove $key[stuff here]</sup>, but simply move the stuff to $key</sup>[stuff here]
I've tried using $1-$4 and \\1-\\4 and I can't seem to get the text to be added after </sup>
Try this;
$text = preg_replace(
'#<sup>((?:(?!</?sup).)*)'.$key.'((?:(?!</?sup).)*)</sup>#is',
'<sup>'.$val.'</sup>\1\2',
$text
);
The (?:...)* bit isn't actually a sub-pattern, and is therefor not available using backreferences. Also, if you use ' rather than " for string literals, you will only need to escape \ and '
// Cheers, Morten
You have to combine preg_match(); and preg_replace();
You match the desired stuff with preg_match() and store in to the variable.
You replace with the same regex to empty string.
Append the variable you store to at the end.

Remove spaces from the beginning and end of a string

I am pretty new to regular expressions.
I need to clean up a search string from spaces at the beginning and the end.
Example: " search string "
Result: "search string"
I have a pattern that works as a javascript solution but I cant get it to work on PHP using preg_replace:
Javascript patern that works:
/^[\s]*(.*?)[\s]*$/ig
My example:
$string = preg_replace( '/^[\s]*(.*?)[\s]*$/si', '', " search string " );
print $string; //returns nothing
On parse it tells me that g is not recognized so I had to remove it and change the ig to si.
If it's only white-space, why not just use trim()?
Yep, you should use trim() I guess.. But if you really want that regex, here it is:
((?=^)(\s*))|((\s*)(?>$))

How can I take a string of text with hyperlinks, unwrap them, and re-insert them in php?

If I have a string of text from Twitter, such as:
$string = "This is a link http://t.co/252351ga to follow.";
How can I unwrap the link, and re-insert into the original string as follows:
$new_string = "This is a link http://www.example.org/article/23534 to follow.";
It's a two-part problem. First you need a regex to find and extract the URLs. It's best to use preg_replace_callback there for simplicity. (You'll find any number of nicer regexs, if you use the search.)
= preg_replace_callback('#http://\S+#', "replace_url_callback", $html)
Second, you either use a shortened URL expansion service/API, or request the URLs yourself and check for redirects or the according meta tag in the response. (For example: http://jamiethompson.co.uk/web/2010/05/18/expanding-short-urls-with-php-expand_url-php-function/ - Forgot the service name I read about lately.. Nevermind, it's simply called "LongURL.org". Not affiliated.)
You probably want to use something like preg_replace and use a pattern to match URLs and replace the match with your own URL.
EDIT:
You can find a good URL regexp here:
http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/
Then use it as follows:
$string = "This is a link http://t.co/252351ga to follow.";
$pattern = ''; //the pattern from the link
$replacement = 'http://www.example.org/article/23534';
echo preg_replace($pattern, $replacement, $string);

Categories