Changing Numeric and Delimeter only

Blockquote
$var=‘I have many Delimeters, i.e. 123D, abcD, 9D, goodD, badD, and good185007D’;
echo str_replace(‘D’,‘NumericDelimeter’,$var);

The code above produces the result below.

Blockquote
I have many Delimeters, i.e. 123NumericDelimeter, abcNumericDelimeter, 9NumericDelimeter, goodNumericDelimeter, badNumericDelimeter, and good185007NumericDelimeter

I like to change numberic and delimeter only.

my target result is the following…

Blockquote
I have many Delimeters, i.e. 123NumericDelimeter, abcD, 9NumericDelimeter, goodD, badD, and good185007NumericDelimeter

Well no it wouldnt, because it would replace the D in “Delimeters” with “NumericDelimeter” and you’d end up with I have many NumericDelimeterelimeters, i.e. 123NumericDelimeter, abcNumericDelimeter, 9NumericDelimeter, goodNumericDelimeter, badNumericDelimeter, and good185007NumericDelimeter

What you’re trying to reference is a preg_replace call, rather than a str_replace one.

I would try creating a function with this approach:

  1. use PHP explode (…); and a space to create an array
  2. create empty $result string
  3. use foreach(…)
  4. check for and apply str_replace if first character is numeric
  5. append the array item to the $result
  6. until there are no more array items
  7. return the $result

Test thoroughly and when ok try to optimise.

OP, what are you actually trying to do? I don’t mean how your trying to do it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.