Home > database >  Php change unordered variable character
Php change unordered variable character

Time:12-02

I want to change a specific character. But the order isn't exact and not only the first one. Here is the variable examples:

  • 123_456_789.jpg
  • 3210_5325_aa.jpg
  • 54321-0888_555_1111.jpg

There are 1000 variables like this. I just want to change all second "_" characters. The result must be like this:

  • 123_456x789.jpg
  • 3210_5325xaa.jpg
  • 54321-0888_555x1111.jpg

I've tried substr and str_replace but I couldn't understand how to do.
Can someone please show me a way to achieve this :)

CodePudding user response:

If the second one is always the last one, you can use strrpos.

<?php

$vals = [
    '123_456_789.jpg',
    '3210_5325_aa.jpg',
    '54321-0888_555_1111.jpg'
];

foreach ($vals as $val) {
    $pos = strrpos($val, '_');
    echo substr($val, 0, $pos) . 'x' . substr($val, $pos   1) . '<BR>';
}

// 123_456x789.jpg
// 3210_5325xaa.jpg
// 54321-0888_555x1111.jpg

If it should be really the second one occurence (independently of real number of occurences), it could be:

<?php

$vals = [
    '123_456_789.jpg',
    '3210_5325_aa.jpg',
    '54321-0888_555_1111_32.jpg'
];

foreach ($vals as $val) {
    $pos = strpos($val, '_'); // 1st '_'
    $pos2 = strpos($val, '_', $pos   1); // 2nd '_'
    echo substr($val, 0, $pos2) . 'x' . substr($val, $pos2   1) . '<BR>';
}

// 123_456x789.jpg
// 3210_5325xaa.jpg
// 54321-0888_555x1111_32.jpg

The second variant is regex, of course. I've showed you strpos/strrpos variants due to the question.

CodePudding user response:

You can use a nested search/replace operation:

$f=[
    '123_456_789.jpg',
    '3210_5325_aa.jpg',
    '54321-0888_555_1111.jpg',
    '____.___'
];

foreach($f as $s) {
$s[strpos($s,"_") 1 strpos(substr($s,strpos($s,"_") 1),"_")]="x";
echo $s.PHP_EOL;
}

Output:

123_456x789.jpg
3210_5325xaa.jpg
54321-0888_555x1111.jpg
_x__.___

First, find the position of the first underscore:

strpos($s,"_")

Take a substring of the string from the next character

substr($s,strpos($s,"_") 1)

and find the position of the next underscore

strpos(substr($s,strpos($s,"_") 1),"_")

Add in the other values, and use the [] notation to edit the string.

Teh Playground!

CodePudding user response:

One option is to match only the second underscore using a pattern and replace the match with x

^[^\s_] _[^\s_] \K_
  • ^ Start of string
  • [^\s_] _[^\s_] Match the first _ and followed by optional chars other than _
  • \K_ Forget what is matched so far using \K and then match the _ which

Regex demo

Or a bit more specific pattern and assert ending with .jpg

^[^\s_] _[^\s_] \K_(?=\S*\.jpg$)

Regex demo

$re = '/^[^\s_] _[^\s_] \K_/m';
$str = '123_456_789.jpg
3210_5325_aa.jpg
54321-0888_555_1111.jpg';

echo preg_replace($re, 'x', $str);

Output

123_456x789.jpg
3210_5325xaa.jpg
54321-0888_555x1111.jpg
  • Related