Jump to content

Trying to combine two regex into one..


Scooby08

Recommended Posts

Is there a way to combine these two lines to work as one? They both work separately..

 

<?php
preg_replace('/^[0-9]+/','+$0',$string);
preg_replace('/[^A-Za-z0-9]+$/','.5',$string);
?>

 

Am checking numbers that could be any of the following (left of "=" is the original and the right is what I'm trying to achieve; the "½" is a special character, not 1/2):

 

5 = +5

-5 = -5

5½ = +5.5

-5½ = -5.5

 

I'm rather new to regex so maybe there's a better way to write what I have as well..

 

Thanks!!

 

 

 

 

Link to comment
Share on other sites

You can't really do that in one pattern. Well you can but there's no real point since they perform different tasks. Rather than calling preg_replace twice though you could pass it arrays.

 

$patterns = array('/^[0-9]+/','+$0');
$replacements = array('/[^A-Za-z0-9]+$/','.5');

$output = preg_replace($patterns, $replacements, $input);

Also I'm certain that can't be the best way to achieve what your after, but for any meaningful help we would need a sample of various inputs (ie values you pass in as $string) as well as the expected outputs.

Link to comment
Share on other sites

I was just checking somebodies awake... that should of course have read...

 

$patterns = array('/^[0-9]+/','/[^A-Za-z0-9]+$/');
$replacements = array('+$0','.5');

Props to salathe for noticing this oversigh... *ahem* deliberate mistake.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.