-2

I have an array containing links. I am trying to cut a part of those links. For example:

$array = [
  "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
  "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];

I want change these links like below:

array(2) {
  [0]=>
  string(91) "https://eksisozluk.com/merve-sanayin"
  [1]=>
  string(91) "https://eksisozluk.com/merve-sanayin"
  [2]=>
}

Is there any possible way to edit array items?

yivi
  • 42,438
  • 18
  • 116
  • 138

2 Answers2

1

Given the array:

$array = [
    "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
    "https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];

Using array_walk() (modifies the array in place).

Using a regular expression this time:

function filter_url(&$item)
{
    preg_match('|(https:\/\/\w+\.\w{2,4}\/\w+-\w+)-.+|', $item, $matches);
    $item = $matches[1];
}

array_walk($array, 'filter_url');

(See it working here).

Note that filter_url passes the first parameter by reference, as explained in the documentation, so changes to each of the array items are performed in place and affect the original array.

Using array_map() (returns a modified array)

Simply using substr, since we know next to nothing about your actual requirements:

function clean_url($item)
{
    return substr($item, 0, 36);
}

$new_array = array_map('clean_url', $array);

Working here.


The specifics of how actually filter the array elements are up to you.

The example shown here seems kinda pointless, since you are setting all elements exactly to the same value. If you know the lenght you can use substr, or you could just could write a more robust regex.

Since all the elements of your input array are the same in the example, I am going to assume this doesn't represent your actual input.

You could also iterate the array using either for, foreach or while, but either of those options seems less elegant when you have specific array functions to deal with this kind of situation.

yivi
  • 42,438
  • 18
  • 116
  • 138
  • Good demonstration of those methods. You might want to point out that the ampersand `&` is needed for array_walk() to modify the value and explain that it means `$item` is a reference. – D.Go Dec 11 '18 at 08:31
0

There are multiple ways. One way is to iterate over the items and clip them with substr().

$arr = array("https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular");

for ($i = 0; $i < count($arr); $i++)
{
    $arr[$i] = substr($arr[$i], 0, 36);
}
D.Go
  • 171
  • 9