PHP regex replace from string to string - php

I want to replace a section of a string based that starts with one string and ends with another, and I want the section between also replaced. I think this is possible using regex but I cant' seem to find any decent examples showing this.
For Example:
I have "http://www.website.com" and I want to replace from "www" to "com" with "123xyz".
So"http://www.website.com/something" becomes "http://123xyz/something.
I am assuming I have to use preg_replace(), and I think the regex should start with "^www" and end with "com$", but I cant seem to get a grasp of the syntax of regex enough to create the desired effect.
please help

With reference to your example , you can try like this
$string = 'http://www.website.com/something';
$pattern = '/www(.*)com/';
$replacement = '123xyz';
echo preg_replace($pattern, $replacement, $string);

$phrase = "http://www.website.com";
$phraseWords = array("www", "com");
$replaceTo = array("123xyz", "something");
$result = str_replace($phraseWords, $replaceTo, $phrase);
echo $result;

Thanks so much to both #CodingAnt and #PHPWeblineindia for your great answers. Using #CodingAnt's answer (and some more research I did online) I wrote this function:
function replaceBetween(&$target, $from, $to, $with){
if(strpos($target, $from)===false)return false;
$regex = "'".$from."(.*?)".$to."'si";
preg_match_all($regex, $target, $match);
$match = $match[1];
foreach($match as $m) $target = str_replace($from.$m.$to, $with, $target);
return $target;
}
It seems to work pretty well. I hope someone finds this useful.

Related

How to get last part of a string?

I have this string:
"application/controllers/backend"
I want get:
backend
of course the backend it's dynamic, so could be change, so I'm looking for a solution that allow me to get only the last part of the string. How I can do that?
You can take the advantage of basename() to get the last part
in your case, it will be
basename("application/controllers/backend");
Output:
backend
Some thing like this :
echo end(explode("/", $url));
If this thorws error then do :
$parts = explode("/", $url);
echo end($parts);
$arr = explode ("/", $string);
//$arr[2] is your third element in the string
http://php.net/manual/en/function.explode.php
Just use
basename("application/controllers/backend");
http://php.net/manual/en/function.basename.php
And, if you want to do it with a regex:
$result = (preg_match('%.*[/\\\\](.*?)$%', $url, $regs)) ? $regs[1] : '';
You did ask initially for a solution with regex, so, although the other answers haven't involved regex, here is one approach which does.
You can use preg_match and str_replace for this:
$string = '"application/controllers/backend"';
preg_match('/[^\/]+"/', $string, $matches);
$last_item = str_replace('"','',$matches[0]);
$last_item is now a string containing the word backend.

How to remove only links from string and nothing more

I have string: Some text (some text) anylink.com www.anylink.com http://anylink.com R.I.O one-www.link.com
I have this code:
$pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "";
$name = preg_replace($pattern, $replacement, $name);
It removes fine: anylink.com, www.anylink.com, http://anylink.com
But its also remove word R.I.O and one- how I can avoid this?
Thanks for help.
I believe that you should be sure of what is really a link or not
you need to find a pattern
I realize that all your links may end with .com
so try this regex "[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+.com$"
but if you need .com.anything or .com/anything
"[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+.com.*$"

Simple str_replace() making things wrong - WordPress

I need some special filtering to certain text all over my website, like below:
function special_text( $content ) {
$search_for = 'specialtext';
$replace_with = '<span class="special-text"><strong>special</strong>text</span>';
return str_replace( $search_for, $replace_with, $content );
}
add_filter('the_content', 'special_text', 99);
It's doing thing in an excellent way, BUT...
in content if there's any link like: <a title="specialtext" href="http://specialtext.com">specialtext</a> then the title and href texts also changed and the link becomes broken.
How can I make exception there?
Is there a way I can put some exceptions in an array and str_replace() simply skip 'em?
You should use regular expression and use function preg_replace() to replace matched string. Here is the full implementation of your special_text() function.
function special_text( $content ) {
$search_for = 'specialtext';
$replace_with = '<span class="special-text"><strong>special</strong>text</span>';
return preg_replace( '/<a.*?>(*SKIP)(*F)|'.$search_for.'/m', $replace_with, $content );
}
In the following regular expression first, using <a.*?> - everything between <a...> is matched and using (*SKIP)(*F)| it is skipped and then from anything else $search_for is matched (in your case it's specialtext).
Jezzabeanz quite got it except you can simplify it still with:
return preg_replace("/^def/", $replace_with, $content);
If you just want to change the text between the the a tags then a regular expression works wonders.
Here is something I used when I was pulling data from emails sent to me:
(?<=">)(.*?\w)(?=<\/a)
returns "specialtext"
It also returns "specialtext test" if there is whitespace.
Regular expressions are definitely the way to go.
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
Source
And then do a replace on the returned matches.

PHP: preg_replace() to get "parent" component of NameSpace

How can I use the preg_replace() replace function to only return the parent "component" of a PHP NameSpace?
Basically:
Input: \Base\Ent\User; Desired Output: Ent
I've been doing this using substr() but I want to convert it to regex.
Note: Can this be done without preg_match_all()?
Right now, I also have a code to get all parent components:
$s = '\\Base\\Ent\\User';
print preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Ent
But I only want to return Ent.
Thank you!
As Rocket Hazmat says, explode is almost certainly going to be better here than a regex. I would be surprised if it's actually slower than a regex.
But, since you asked, here's a regex solution:
$path = '\Base\Ent\User';
$search = preg_match('~([^\\\\]+)\\\\[^\\\\]+$~', $path, $matches);
if($search) {
$parent = $matches[1];
}
else {
$parent = ''; // handles the case where the path is just, e.g., "User"
}
echo $parent; // echos Ent
I think maybe preg_match might be a better choice for this.
$s = '\\Base\\Ent\\User';
$m = [];
print preg_match('/([^\\\\]*)\\\\[^\\\\]*$/', $s, $m);
print $m[1];
If you read the regular expression backwards, from the $, it says to match many things that aren't backslashes, then a backslash, then many things that aren't backslashes, and save that match for later (in $m).
How about
$path = '\Base\Ent\User';
$section = substr(strrchr(substr(strrchr($path, "\\"), 1), "\\"), 1);
Or
$path = '\Base\Ent\User';
$section = strstr(substr($path, strpos($path, "\\", 1)), "\\", true);

Parsing a Source With REGEX

I want to get all Performance ID's from this page .
<?php
$content = file_get_contents("http://www124.popmundo.com/Common/Performances.asp?action=ComingPerformances&ArtistID=1962457");
$regex = "Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)";
//$regex = "/Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)/";
//$regex = "/Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)/s";
//all pattern variations tested, not working
if(preg_match_all($regex, $content, $m))
print_r($m);
else
echo "FALSE";
// this is returning FALSE
Use & instead of & in your regex.
Try this:
$regex = "/Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)/";
It looks like an escape problem. Not knowing php, I would guess one of these
might fix it:
$regex = 'Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)';
or
$regex = "Performances\\.asp\\?action=Arrangements&PerformanceID=([0-9]+)";
or
$regex = '/Performances\.asp\?action=Arrangements&PerformanceID=([0-9]+)/';

Categories