Mohammadreza Ahmadpour
Mohammadreza Ahmadpour

Reputation: 111

Delete a duplicate string appearing in all array elements

In Laravel I can return data from Google analytics to get most visited page with this command:

$FilterData =$this->parseResults($data)->pluck('url');

It will be return this URLs:

 [
    "/products/r4-04",
    "/products/r6-01",
    "/products/cu3-20",
    "/products/r4-51",
    "/products/zp-1",
    "/products/r5-31",
    "/products/cu3-64",
    "/products/cu6-01-1",
    "/products/cu6-01-2",
    "/products/r4-14",
    "/products/t4-74",
    "/products/cu-001",
    "/products/cu5-18",
    "/products/zp-8",
    "/products/td6-01",
    "/products/t4-14",
    "/products/c6-01"
]

Now I want to remove all /products/ word from this and find the products by slug.

Upvotes: 0

Views: 47

Answers (3)

Sehdev
Sehdev

Reputation: 5662

You can simple use str_replace to achieve the same.

Assuming your variable as $products

 $array =  str_replace('/products/', '', $products);
 dd($array);

Upvotes: 0

Youssef Saoubou
Youssef Saoubou

Reputation: 591

<?php
$products =  [
    "/products/r4-04",
    "/products/r6-01",
    "/products/cu3-20",
    "/products/r4-51",
    "/products/zp-1",
    "/products/r5-31",
    "/products/cu3-64",
    "/products/cu6-01-1",
    "/products/cu6-01-2",
    "/products/r4-14",
    "/products/t4-74",
    "/products/cu-001",
    "/products/cu5-18",
    "/products/zp-8",
    "/products/td6-01",
    "/products/t4-14",
    "/products/c6-01"
];
function replace($product) {
   return str_replace('/products/', '', $product);  
}
$products = array_map('replace', $products);

Upvotes: 0

Oto Shavadze
Oto Shavadze

Reputation: 42773

If you need just remove /products/ from every array value, you can use str_replace for this:

$FilterData =$this->parseResults($data)->pluck('url');
$FilterDataNew = str_replace("/products/","",$FilterData);
var_dump($FilterDataNew);

Upvotes: 1

Related Questions