I want to be able to search for a certain word in a string, and append and prepend characters to every instance of that word.
example:
I like cats, cats are awesome! I wish I had cats!
becomes:
I like (cats), (cats) are awesome! I wish I had (cats)!
I know I could use
str_replace( 'cats', '(cats)', $string );
but I would have to write "cats" twice.
I want a method that only requires me to write it once.
$search = 'cats';
preg_replace('/' . preg_quote($search, '/') . '/', '($0)', $string);
Paraphrased from the preg_replace documentation:
The replacement string may contain references of the form $n. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. $0 refers to the text matched by the whole pattern.
use a preg_replace() with back references: http://php.net/manual/en/function.preg-replace.php
preg_replace("/cats/smi","($0)",$string);
You commented:
I have a huge plain text list of values I need to parenthesize, and I
wanted to make it easier to write the code.
Since you're going to be doing many replacements (expensive cpu-wise), and you're wanting to simply shorten your coding time, why not also save CPU by wrapping str_replace()?
function str_wrap($needle,$prefix,$suffix,$haystack) {
return str_replace($needle, $prefix . $needle . $suffix, $haystack);
}
Per the PHP manual:
If you don't need fancy replacing rules (like regular expressions),
you should always use [str_replace()] instead of preg_replace().
Related
Instead of wondering what regex I need for each time I need a regex, I like to learn how to do basic string replacement with regexes.
How do you take one string and replace it with another with regexes in PHP ?
For example how do you take all '/' and replace them with '%' ?
If you just want to do basic string replacement (i.e. replace all 'abc' with '123') then you can use str_replace, which doesn't require using regex. For basic replacements, this will be easier to set up and should run faster.
If you want to use this as a tool to learn regex though (or need more complicated replacements) then preg_replace is the function you need.
You should look into preg_replace. For your question
$string = "some/with/lots/of/slashes";
$new_string = preg_replace("/\//","%",$string);
echo $new_string;
I like to learn how to do basic string replacement with regexes.
That's a little broad for this forum. However, to answer a more specific question like:
For example how do you take all '/' and replace them with '%' ?
You could do that like this:
$result = preg_replace('#\/#', '%', 'Here/is/a/test/string.');
Here is a Rubular that proves the regex.
Note, you are not limited to using the common / delimiter, which means when working with forward slashes it is often easier to change to a different delimiter EG.
$mystring = 'this/is/random';
$result = preg_replace('#/#', '%', $mystring);
This will make '#' the delimiter, rather than the standard '/', so it means you do not need to escape the slash.
I would do this simply with strtr which is very suitable for character mapping, e.g.
strtr('My string has / slashes /', '/', '%');
If you want to also replace the letter a with a dash:
strtr('My string has / slashes /', '/a', '%-');
As you can see, the second and third argument define the transformation map.
How can I replace a string starting with 'a' and ending with 'z'?
basically I want to be able to do the same thing as str_replace but be indifferent to the values in between two strings in a 'haystack'.
Is there a built in function for this? If not, how would i go about efficiently making a function that accomplishes it?
That can be done with Regular Expression (RegEx for short).
Here is a simple example:
$string = 'coolAfrackZInLife';
$replacement = 'Stuff';
$result = preg_replace('/A.*Z/', $replacement, $string);
echo $result;
The above example will return coolStuffInLife
A little explanation on the givven RegEx /A.*Z/:
- The slashes indicate the beginning and end of the Regex;
- A and Z are the start and end characters between which you need to replace;
- . matches any single charecter
- * Zero or more of the given character (in our case - all of them)
- You can optionally want to use + instead of * which will match only if there is something in between
Take a look at Rubular.com for a simple way to test your RegExs. It also provides short RegEx reference
$string = "I really want to replace aFGHJKz with booo";
$new_string = preg_replace('/a[a-zA-z]+z/', 'boo', $string);
echo $new_string;
Be wary of the regex, are you wanting to find the first z or last z? Is it only letters that can be between? Alphanumeric? There are various scenarios you'd need to explain before I could expand on the regex.
use preg_replace so you can use regex patterns.
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.
i'v got such string <>1 <>2 <>3
i want remove all '<>' and symbols after '<>' i want replace with such expression like www.test.com/1.jpg, www.test.com/2.jpg, www.test.com/3.jpg
is it possible to do with regex? i only know to find '/<>.?/'
preg_replace('/<>(\d+)/g', 'www.test.com/bla/$1.jpg', $input);
(assuming your replaced elements are just numbers. If they are more general, you'll need to replace '\d+' by something else).
str_replace('<>', 'www.test.com/', $input);
// pseudo code
pre_replace_all('~<>([0-9]+)~', 'www.test.com/$1.jpg', $input);
$string = '<>1 <>2 <>3';
$temp = explode(' ',preg_replace('/<>(\d)/','www.test.com/\1.jpg',$string));
$newString = implode(', ',$temp);
echo $newString;
Based on your example, I don’t think you need regex at all.
$str = '<>1 <>2 <>3';
print_r(str_replace('<>', 'www.test.com/', $str));
Regex's allow you to manipulate a string in any fashion you desire, to modify the string in the fashion you desire you would use the following regex:
<>(\d)
and you would use regex back referencing to keep the values you have captured in your grouping brackets, in this case a single digit. The back reference is typically signified by the $ symbol and then the number of the group you are referencing. As follows:
www.test.com/$1
this would be used in a regex replace scenario which would be implemented in different ways depending on the language you are implementing your regex replace method in.
I have strings in my application that users can send via a form, and they can optionally replace words in that string with replacements that they also specify. For example if one of my users entered this string:
I am a user string and I need to be parsed.
And chose to replace and with foo the resulting string should be:
I am a user string foo I need to be parsed.
I need to somehow find the starting position of what they want to replace, replace it with the word they want and then tie it all together.
Could anyone write this up or at least provide an algorithm? My PHP skills aren't really up to the task :(
Thanks. :)
$result = preg_replace('/\band\b/i', 'foo', $subject);
will find all occurences of and where it's a word on its own and replace it with foo. \b ensures that there is a word boundary before and after and.
use preg_replace. You don't need to think so hard about this though you will have to learn a little bit about regexes. :)
Read up on str_replace, or for more complex replacements on Regular Expressions and preg_replace.
Examples for both:
<?php
$str = 'I am a user string and I need to be parsed.';
echo str_replace( 'and', 'foo', $str ) . "\n";
echo preg_replace( '/and/', 'foo', $str ) . "\n";
?>
In response to the comments of this answer, note that both examples above will replace every occurrence of the search string (and), even when it happens to be within another word.
To take care of that you either have to add the word separators to the str_replace call (see the comment of an example), but this will get quite complicated when you want to take care of all common word separators (space, commas, dots, exclamation marks, question marks etc.).
An easier to way to fix this problem is to use the power of regular expressions and make sure, the actual search string is not found within another word. See Tim Pietzcker's example below for a possible solution.