PHP Regex moving selection to different location in string - php

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.

Related

Extract value from between quotes with regex

I have the following string:
feature name="osp"
I need to extract part of the strings out and put them into a new string. The word feature can change and the word inside quotes can change so I need to be able to capture any instance possible. The name=" " part is always the same. The result I need is:
feature osp
I need to filter out the name= and quotes from the string.
I've used this ^\w*\s to get the first feature part but can't figure out how to extract osp from the string using a regex. I've been looking here RegEx: Grabbing values between quotation marks but can't get a regex that combines both to get the result I need. I'm working in PHP so using preg-match at the moment. Can anyone help with this?
I'd go with
(\w+)\s+name\s*=\s*"([^"]*)
It's a little bit slower, but it allows for arbitrary number of spaces and it captures the first word correctly, even with Alexandru's test.
See it work here at regex101.
Regards
Try something like that:
preg_match('/(.+)name="(.+?)"/', $string, $matches);
echo $matches[1] . $matches[2];
An improved version of #vuryss
preg_match('/(.*?)name="(.*?)"/ims', $string, $matches);
echo $matches[1] . $matches[2];

Simple regex replace regardless of middle text php

say I have this
searchpage-20/11111111111?node=15
how would I setup a regex to replace the entire string without worrying about the
11111111111
in the middle as long as the rest matches.
I tried
searchallmp3-20/(.+?)\?node=
You should post the code, to see how you are calling the regex and you need also to describe, what is not working.
I assume you are getting some error message because you are using / without escaping it in your regex and your delimiter is also the /
Two possibilities:
Escape the /
/searchallmp3-20\/(.+?)\?node=/
Use another delimiter
~searchallmp3-20/(.+?)\?node=~
See Delimiters on php.net
I still don't get the replace part of your question. If you want to remove the digits before the ?, you should capture the other parts of the string
~(searchallmp3-20/).+?(\?node=~)
and replace with
`$1$2`
this will result in
searchpage-20/?node=15
Is it this what you want?
How about
<?php
$search = 'searchpage-20/11111111111?node=15';
$reg = '#(searchpage-\d+/)\d+(\?node=\d+)#';
echo preg_replace($reg, '${1}blah${2}', $search);
OUTPUT
searchpage-20/blah?node=15
You should be able to use this:
/searchpage-(\d+)\/(\d+)\?node=(\d+)/
Example usage:
preg_replace('/searchpage-(\d+)\/(\d+)\?node=(\d+)/', '', 'searchpage-20/11111111111?node=15');

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*)(?>$))

Remove part of a string with regex

I'm trying to strip part of a string (which happens to be a url) with Regex. I'm getting better out regex but can't figure out how to tell it that content before or after the string is optional. Here is what I have
$string='http://www.example.com/username?refid=22';
$new_string= preg_replace('/[/?refid=0-9]+/', '', $string);
echo $new_string;
I'm trying to remove the ?refid=22 part to get http://www.example.com/username
Ideas?
EDIT
I think I need to use Regex instead of explode becuase sometimes the url looks like http://example.com/profile.php?id=9999&refid=22 In this case I also want to remove the refid but not get id=9999
parse_url() is good for parsing URLs :)
$string = 'http://www.example.com/username?refid=22';
$url = parse_url($string);
// Ditch the query.
unset($url['query']);
echo array_shift($url) . '://' . implode($url);
CodePad.
Output
http://www.example.com/username
If you only wanted to remove that specific GET param, do this...
parse_str($url['query'], $get);
unset($get['refid']);
$url['query'] = http_build_query($get);
CodePad.
Output
http://example.com/profile.php?id=9999
If you have the extension, you can rebuild the URL with http_build_url().
Otherwise you can make assumptions about username/password/port and build it yourself.
Update
Just for fun, here is the correction for your regular expression.
preg_replace('/\?refid=\d+\z/', '', $string);
[] is a character class. You were trying to put a specific order of characters in there.
\ is the escape character, not /.
\d is a short version of the character class [0-9].
I put the last character anchor (\z) there because it appears it will always be at the end of your string. If not, remove it.
Dont use regexs if you dont have to
echo current( explode( '?', $string ) );

Replacing a string inside a string in PHP

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.

Categories