Reputation: 7077
Please read the code below and comments to see what I'm trying to do. Its hard to explain in a paragraph.
$url_fixx = 'home/sublink/group-view/product/catview1';
// What my variable holds. MY GOAL IS: I want to omit group-view, product and catview1 from this so I use the trick below.
catview has a random number at the end so I use the code below to find the number at the end and it outputs "catview1" in this case
$string = $url_fixx;
$matches = array();
if (preg_match('#(catview\d+)$#', $string, $matches)) {
$catViewCatch = ($matches[1]);
}
// I got this from http://stackoverflow.com/a/1450969/1567428
$url_fixx = str_replace( array( 'group-view/', 'product', 'catview1' ), '', $url_fixx );
// this outputs what I want.
MY QUESTION IS :
//When I replace "catview1" with $catViewCatch, the whole str_replace doesnt work.
$url_fixx = str_replace( array( 'group-view/', 'product', $catViewCatch), '', $url_fixx );
Why is that? and what am I doing wrong?
PS: Also my url sometimes changes to something like this.
$url_fixx = 'home/sublink/group-view/anotuer-sublink/123-article'
How can I tackle all these ?
Upvotes: 1
Views: 88
Reputation: 2823
Both of your examples output the exact same thing. The below code demonstrates this:
<?php
$url_fixx = 'home/sublink/group-view/product/catview1';
$string = $url_fixx;
$matches = array();
if (preg_match('#(catview\d+)$#', $string, $matches)) {
$catViewCatch = ($matches[1]);
}
echo str_replace( array( 'group-view/', 'product', 'catview1' ), '', $url_fixx );
echo '<br />';
echo str_replace( array( 'group-view/', 'product', $catViewCatch), '', $url_fixx );
?>
Also, you might consider using preg_replace instead as it will accomplish the task with less code:
echo preg_replace('#group-view/product/catview[0-9]+#','',$url_fixx);
Upvotes: 3