I’ve looked around and understand how to replace a string between two characters or how to replace one instance of a string between two strings and have played around with those functions but have come up empty.
I want to replace all occurrences of a string between two other strings. In the lines below, I want to replace the text between “Insert here” and “done”
$string =“Insert here SOME TEXT done blah blah Insert here SOME OTHER TEXT done blah blah harumph Insert here SOME MORE TEXT done”
I’ve been trying to modify the function here:
http://codepad.org/tWyiffC5
Use RegEx for that:
echo preg_replace('/Insert here(.*?)done/', '<tag>$1</tag>', $string);
// <tag> SOME TEXT </tag> blah blah <tag> SOME OTHER TEXT </tag> blah blah harumph <tag> SOME MORE TEXT </tag>
Example
RegEx explanation
Related
I have little confidence when it comes to regular expressions. Writing this in PHP code.
I need to be able to filter out strings that follow this format, where the numbers can be 4~6 digits (numeric only):
$input = "This is my string with a weird ID added cause I'm a weirdo! (id:11223)";
I could simply remove the last word by finding the last position of a space via strrpos(); (it appears none of them have a trailing space from JSON feed), then use substr(); to cut it. But I think the more elegant way would be a substring. The intended output would be:
$output = trim(preg_replace('[regex]', $input));
// $output = "This is my string with a weird ID added cause I'm a weirdo!"
So this regex should match with the brackets, and the id: portion, and any contiguous numbers, such as:
(id:33585)
(id:1282)
(id:9845672)
Intending to use the preg_replace() function to remove these from a data feed. Don't ask me why they decided to include an ID in the description string... It blows my mind too why it's not a separate column in the JSON feed altogether.
Try using the pattern \(id:\d+\):
$input = "Text goes here (id:11223) and also here (id:33585) blah blah";
echo $input . "\n";
$output = preg_replace("/\(id:\d+\)/", "", $input);
echo $output;
This prints:
Text goes here (id:11223) and also here (id:33585) blah blah
Text goes here and also here blah blah
There is an edge case here, which you can see in the possible (unwanted) extract whitespace left behind after the replacement. We could try to get sophisticated and remove that too, but you should state what you expected output is.
I'm writing a parser and I need to extract words that are between double pipes using php
For example I want to extract the 'ipsum' from the string below
Lorem ||ipsum|| blah
If there are multiple words between double pipes, they should be extracted as well
Clarification
When I say multiple words I don't mean this: ||word another word||
I mean this
||Word1|| blah blah (newline)
blah ||Word2||
Clarification part 2
the ||quick|| brown fox ||jumps|| over the lazy ||dog||
What should be extracted should be the words 'quick', 'jumps' and 'dog'
Sorry for the confusion... There probably are some right answers below, I'll pick one once I confirm it tomorrow at work :)
What about a simple
$array = explode('||', $string);
After that, you probably want to trim the array values using trim().
See also http://www.php.net/explode and http://www.php.net/trim
Here is a regex solution: http://regex101.com/r/vE9pY9
/\Q||\E[^|]+\Q||\E/
This will not accept pipes to be a part of the word though. If that is a requirement the regex has to be remade.
Try this:
if(preg_match('/\|\|(.*)\|\|/', $str, $matches) === 1){
echo $matches[1];
}
Or if there are multiple ||, try this:
if(preg_match_all('/\|\|(.*?)\|\|/', $str, $matches) !== FALSE){
print_r($matches[1]);
}
I think I know what your looking for:
\|\|[a-zA-Z0-9]+\|\|
This should satisfy your example:
||Word1|| blah blah (newline)
blah ||Word2||
Of picking Word1 and Word2 out.
You will need to strip off the || on either side.
There is a way to use regex to strip the || out as well but KISS. It is easier to read and easier to, in general, strip this stuff out later. So you have a simple regex with a simple trim.
Hope it helps,
I have a PHP page that is reading text stored in a MYSQL database table.
The text might look something like this
Bob: Hi blah blah
(Bob walking around)
Fred Johnson: blah blah blah
Bob: Something something: something
I want to do a preg_replace to bold everything that comes before the first colon in each line.
So in this situation only the names would be bold and on that last line "Something something" would not be bold
What I have now bolds everything on each line that comes before any colon
$reg='(.*\w:)';
$text = preg_replace("/".$reg."/", "<b>\${1}</b>", $text);
You can use:
$reg='^([^:]*:)';
See it
The ^ symbol is used to match the beginning of a line. Prepend that to the beginning of your regex and it will assure that the match starts at the beginning of the current line :-)
I'm trying to identify if the user has typed someone else's username if the typed an at symbol (#) before it, much like on twitter. My function can recognise the # symbol and the username after it, but it includes the a spacebar after it (if there was one).
Here's my regex stuff
/#([A-Za-z0-9_]+)(\s|\Z)/
So let's say that a user typed
#testificate blah blah blah
My function would select the following (between the | symbols)
|#testificate |blah blah blah
When what I actually want is for it to select
|#testificate| blah blah blah
It includes the space afterwards and that's not what I want. Is there a better way to do this? I'm turning the # tags into links with a preg_replace, can anyone help me out? Thanks
why you add (\s|\Z) ?
\s space
\Z End of subject or newline at end
Regex: /#([A-Za-z0-9_]+)/
Edit:
davidchambers's suggestion
Shorter Regex: /#(\w)+/
I have a situation in which I parse a body of text and replace certain phrases with links. I then need to re-parse the string to replace a second set of phrases with links. The problem arises at this point, where certain words or phrases in the second set can be substrings of phrases already replaced in the first pass.
Example: The string "blah blah grand canyon blah" will become "blah blah grand canyon blah" after the first pass. The second pass might try to replace the word "canyon" with a link, so the resulting, broken, text would read: "blah blah grand <a href="#">canyon</a> blah".
So I've been trying to use preg_replace and a regular expression to prevent nested <a> tags from occurring - by only replacing text which is not already in a link. I have tried to regexes that check based on whether there are </a> tags further on in the text but can't get these to work.
Maybe another approach is required?
Many thanks in advance!
Dave
This might work for all passes:
$string = preg_replace('/([^>]|^)grand canyon\b/','$1<a href=#>grand canyon</a>',$string);
EDIT: assuming you can afford missing when the text contains stuff like "amazonas>grand canyon"
For the second pass, you could use a regex such as:
(<a[^>]*>.*?</a>)|grand
This regex matches either a link, or the word "grand". If the link is matched, it is captured into the first (and only) capturing group. If the group matched, simply re-insert the existing link. If the word grand matches, you know it's outside a link, and you can turn it into a link.
In PHP you can do this with preg_replace_callback:
$result = preg_replace_callback('%(<a[^>]*>.*?</a>)|grand%', compute_replacement, $subject);
function compute_replacement($groups) {
// You can vary the replacement text for each match on-the-fly
// $groups[0] holds the regex match
// $groups[n] holds the match for capturing group n
if ($groups[1]) {
return $groups[1];
} else {
return "<a href='#'>$groups[0]</a>";
}