Assume i have the following hrefs:
.... href="http://localhost/centboox/usedtextbooks/desc/30" ....
I would like to through all of them and add ** just before closing the href's double quotation:
... href="http://localhost/webname/pagename/desc/30*******" ...
Asterisks represent some input e.g. ?q=all&a=search_text
How can i do this via preg_replace in PHP.
Thanks
$result = preg_replace('/href="[^"]*/', '\0********', $subject);
Any reason you can't just concatenate if you're going to ALWAYS do it to the end of the string?
// Assuming you're array is already filled out...
$somethingToAppend = "?q=all&a=search_text"
foreach($hrefs as $key => $value) {
$hrefs[$key] = $value + $somethingToAppend;
}
Cheers
Here's a simple example:
$href = <<<EOHTML
LINK
EOHTML;
$href = preg_replace("/href=\"([^\"]*)\"/",
"href=\"$1**\"", $href);
echo $href;
In the regex pattern I'm looking for href="(something)" and I'm replacing it with href="(something)**".
here is examples of preg_replace it may get useful to you. check below link
http://php.net/manual/en/function.preg-replace.php
Related
$str='<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = preg_replace('/.html\?(.*?)/','.html',$str);
echo $str;
I need get
<p>http://domain.com/1.html</p>
<p>http://domain.com/2.html</p>
<p>http://domain.com/3.html</p>
<p>http://domain.com/4.html</p>
remove ?u=*number* from every words last part. thanks.
Change this line:
$str = preg_replace('/.html\?(.*?)/','.html',$str);
into this:
$str = preg_replace('/.html\?(.*?)</','.html<',$str);
An alternative to the other answers:
preg_replace("/<p>([^?]*)\?[^<]*<\/p>/", "<p>$1</p>", $input);
This will match all types of urls with url variables, not only the ones with html-files in them.
For example, you can also extract these types of values:
<p>http://domain.com/1.php?u=1234576</p>
<p>http://domain.com?u=1234576</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users?uid=123</p>
With an output of:
<p>http://domain.com/1.php</p>
<p>http://domain.com</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users</p>
This code will load the url's into an array so they can be handled on the fly:
$str = '<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = str_replace("<p>","",$str);
$links = preg_split('`\?.*?</p>`', $str,-1,PREG_SPLIT_NO_EMPTY);
foreach($links as $v) {
echo "<p>".$v."</p>";
}
i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ?
For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)
http://webarto.com/62/random-sentence-spinning-function
function get_random($matches)
{
$rand = array_rand($split = explode("|", $matches[1]));
return $split[$rand];
}
function show_randomized($str)
{
$new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str);
if ($new_str !== $str) $str = show_randomized($new_str);
return $str;
}
Applied on your text file... http://ideone.com/rkuf6
strip off initial and ending curly braces, you can use trim()
explode the resulting string on | using explode()
use array_rand() for the array you had in last step
Will not work with nested({a|x {b|c} y|z})!
function doStuff($from){
$to="";
while(($pos=strpos($from,'{'))!==false){
$to.=substr($from,0,$pos);
$from=substr($from,$pos);
$closepos=strpos($from,'}');
$arr=explode('|',substr($from,1,$closepos-1));
$to.=$arr[array_rand($arr)];
$from=substr($from,$closepos+1);
}
return $to.$from;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP String Manipulation: Extract hrefs
I am using php and have string with content =
Click here
I need to get rid of everything except "www.something.com"
I assume this can be done with regular expressions.
Any help is appreciated!
Thank you
This is very easy to do using SimpleXML:
$a = new SimpleXMLElement('Click here');
echo $a['href']; // will echo www.something.com
Give this a whirl:
$link = 'Click here';
preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $link, $result);
if (!empty($result)) {
# Found a link.
echo $result['href'][0];
}
Result: www.something.com
Updated: Now requires the quoting style to match, addressing the comment below.
I would suggest following code for this:
$str = 'Click here';
preg_match('/href=(["\'])([^\1]*)\1/i', $str, $m);
echo $m[2] . "\n";
OUTPUT
www.something.com
This will take care of both single quote ' and double quote " in the href link.
Assuming that is ALWAYS the format of the variable, below should do the trick. If the content may not be a link, this won't work. Essentially it looks for data enclosed within two quotations.
<?php
$string = 'Click here';
$pattern = '/"[a-zA-Z0-9.\/\-\?\&]*"/';
preg_match($pattern, $string, $matches);
print_r($matches);
?>
As probably you didn't meant your question that easy, but this does exactly what you're asking for:
$link = 'Click here';
$href = substr($link, 9, -16);
$href is:
string(17) "www.something.com"
As a regular expression it can be expressed it as this is:
$href = preg_match('(^Click here$)', $link, $matches) ? $matches[1] : die('Invalid input data.');
Is this helpful?
I have a string, for example "[{XYZ123}] This is a test" and need to parse out the content in between the [{ and }] and dump into another string. I assume a regular expression is in order to accomplish this but as it's not for the faint of heart, I did not attempt and need your assistance.
What is the best way to pull the fragment in between the [{ and }]? Thanks in advance for your help!
<?php
$str = "[{XYZ123}] This is a test";
if(preg_match('/\[{(.*?)}\]/',$str,$matches)) {
$dump = $matches[1];
print "$dump"; // prints XYZ123
}
?>
$str = "[{XYZ123}] This is a test";
$s = explode("}]",$str);
foreach ($s as $k){
if ( strpos($k,"[{") !==FALSE ){
$t = explode("[{",$k); #or use a combi of strpos and substr()
print $t[1];
}
}
The regex would be (?=\[\{).*(?=\}\]), though I don't know if php supports look aheads.