Replace text if it matches another piece of text - php

So I have the following code to remove "page=" from a string. My problem now is that I want to query through "$qs_final" to check if it contains "price_range" and if so replace it with another piece of text. The price range variable is attached to "attr=" so I can't really use a $_GET request as other information is stored within it. The price_range variable also has the layout of "price_range_20".
<?php
$querystring = explode("&",$_SERVER['QUERY_STRING']);
$qs_nos = 0;
$qs_final = "";
while(isset($querystring[$qs_nos])) {
if(!ereg("page=",$querystring[$qs_nos])) {
$qs_final .= $querystring[$qs_nos]."&";
}
$qs_nos++;
}
if (strpos($qs_final,'price_range') !== false) {
print "true";
}
?>

str_replace().
$new_string = str_replace($what_to_replace, $what_to_replace_it_with, $old_string);
EDIT: To replace data, you need preg_replace(). In your case to remove "price_range" and all numbers and underscores directly after it, use this:
$new_string = preg_replace("/price_range[0-9_]+/", "", $old_string);

Related

PHP match and replace whole word

Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here

Replacing corrupt e-mail addresses in a file, using PHP

I have a file file.txt containing a list of emails
email#domain.com
email#domain2.com
email#domain3.com
email#domain4.com
email#domain5.com
#domain.com
email#domain6.com
email#domain7.com
I need to remove #domain.com from the list. I am using this code:
file_put_contents('file.txt',
str_replace("#domain.com","",file_get_contents('file.txt')));
But this also removes #domain.com from email#domain.com, making it an incorrect list.
How can I do this?
You could also use regex to match a whole line. From the top of my head this would be:
<?php
file_put_contents('file.txt',
preg_replace("/^#domain\.com$/m","",file_get_contents('file.txt')));
If you want to delete the line instead of making it empty the regex would be "/^#domain\.com[\n]$/m"
you could try using a regex something like (^#domain\.com) should replace only #domain.com if the # is the begining of the sentence
You should use preg_replace: http://php.net/manual/en/function.preg-replace.php on each line.
This will remove every e-mail address, which does not have username at the beginning.
$file = new SplFileObject("file.txt");
$emailAddresses = array();
while (!$file->eof()) {
$email = trim(preg_replace("/^#(.*)$/", "", $file->fgets())); // If you only want to remove specific addresses from a specific domain, change (.*) to domain\.com
if (strlen($email)) {
$emailAddresses [] = $email;
}
}
file_put_contents("file.txt", join(PHP_EOL, $emailAddresses));
You could determine the position of the # sign and replace only if it's the first character in the line.
function replacethis($file){
$str = '';
$a = file_get_contents($file);
foreach ($a as $b) {
if (strpos($b,'#') == 0) {
$str .= str_replace('#domain.com','',$b)."<br>"; }
else {
$str .= $b."<br>";
}}
return $str;
}
file_put_contents('file.txt', replacethis('file.txt'));

Replace multiple occurrences of a string with different values

I have a script that generates content containing certain tokens, and I need to replace each occurrence of a token, with different content resulting from a separate loop.
It's simple to use str_replace to replace all occurrences of the token with the same content, but I need to replace each occurrence with the next result of the loop.
I did see this answer: Search and replace multiple values with multiple/different values in PHP5?
however it is working from pre-defined arrays, which I don't have.
Sample content:
This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated
elsewhere.
I need to replace each occurrence of %%token%% with content generated, for argument's sake, by this simple loop:
for($i=0;$i<3;$i++){
$token = rand(100,10000);
}
So replace each %%token%% with a different random number value $token.
Is this something simple that I'm just not seeing?
Thanks!
I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.
It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this:
$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i) {
// The last piece of the string has no token after it, so we special-case it
if ($i == count($shrapnel) - 1)
$newStr .= $shrapnel[$i];
else
$newStr .= $shrapnel[$i] . rand(100,10000);
}
I know this is an old thread, but I stumbled across it while trying to achieve something similar. If anyone else sees this, I think this is a little nicer:
Create some sample text:
$text="This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated
elsewhere.";
Find the search string with regex:
$new_text = preg_replace_callback("|%%token%%|", "_rand_preg_call", $text);
Define a callback function to change the matches
function _rand_preg_call($matches){
return rand(100,10000);
}
Echo the results:
echo $new_text;
So as a function set:
function _preg_replace_rand($text,$pattern){
return preg_replace_callback("|$pattern|", "_rand_preg_call", $text);
}
function _rand_preg_call($matches){
return rand(100,10000);
}
I had a similar issue where I had a file that I needed to read. It had multiple occurrences of a token, and I needed to replace each occurrence with a different value from an array.
This function will replace each occurrence of the "token"/"needle" found in the "haystack" and will replace it with a value from an indexed array.
function mostr_replace($needle, $haystack, $replacementArray, $needle_position = 0, $offset = 0)
{
$counter = 0;
while (substr_count($haystack, $needle)) {
$needle_position = strpos($haystack, $needle, $offset);
if ($needle_position + strlen($needle) > strlen($haystack)) {
break;
}
$haystack = substr_replace($haystack, $replacementArray[$counter], $needle_position, strlen($needle));
$offset = $needle_position + strlen($needle);
$counter++;
}
return $haystack;
}
By the way, 'mostr_replace' is short for "Multiple Occurrence String Replace".
You can use the following code:
$content = "This is an example of %%token%% that might contain multiple instances of a particular %%token%%, that need to each be replaced with a different piece of %%token%% generated elsewhere.";
while (true)
{
$needle = "%%token%%";
$pos = strpos($content, $needle);
$token = rand(100, 10000);
if ($pos === false)
{
break;
}
else
{
$content = substr($content, 0,
$pos).$token.substr($content, $pos + strlen($token) + 1);
}
}

Extract number from variable

I have this string:
$guid = 'http://www.test.com/?p=34';
How can I extract the value of get var p (34) from the string and have $guid2 = '34'?
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$guid2 = $vars['p'];
If 34 is the only number in the query string, you can also use
echo filter_var('http://www.test.com/?p=34', FILTER_SANITIZE_NUMBER_INT); // 34
This will strip anything not a number from the URL string. However, this will fail the instant there is other numbers in the URL. The solution offered by konforce is the most reliable approach if you want to extract the value of the p param of the query string.
A preg_replace() is probably the quickest way to get that variable, the code below will work if it is always a number. Though konforce's solution is the general way of getting that information from a URL, though it does a lot of work for that particular URL, which is very simple and can be dealt with simply if it unaltering.
$guid = 'http://www.test.com/?p=34';
$guid2 = preg_replace("/^.*[&?;]p=(\d+).*$/", "$1", $guid);
Update
Note that if the URLs can not be guaranteed to have the variable p=<number> in them, then you would need to use match instead, as preg_replace() would end up not matching and returning the whole string.
$guid = 'http://www.test.com/?p=34';
$matches = array();
if (preg_match("/^.*[&?;]p=(\d+).*$/", $guid, $matches)) {
$guid2 = $matches[1];
} else {
$guid2 = false;
}
That is WordPress. On a single post page you can use get_the_ID() function (WP built-in, used in the loop only).
$guid2 = $_GET['p']
For more security:
if(isset($_GET['p']) && $_GET['p'] != ''){
$guid2 = $_GET['p'];
}
else{
$guid2 = '1'; //Home page number
}

Replace a string from a submission with an empty string if string is present

I have tried many combinations and a few different PHP functions, but I still can't figure out why it doesn't work.
Here's the deal.. If someone uses the form and the (in this case) "Title" field ends with " (Part 1)", I want to delete that string, and if it doesn't contain " (Part 1)" I want to set a variable to the Title as it was submitted.
Here is my current script:
<?php
$partInStack = stristr($_POST['Title'], " (Part 1)");
if ($partInStack !== FALSE) {
$Title = str_replace($partInStack, "");
} else {
$Title = $_POST['Title'];
}
?>
You don't need to check stristr first, you can just do the str_replace right away:
$Title= str_replace(" (Part 1)","",$_POST['Title']);
UPDATE
You're original wasn't working because you messed up the parameter list for str_replace http://us.php.net/str_replace:
str_replace($search, $replace, $subject);
There's one parameter missing there in str_replace()
http://php.net/manual/en/function.str-replace.php

Categories