Jump to content

Recommended Posts

@shamuraq

a) the most immediate reason your preg_replace didn't work was because you have spaces between the part of your pattern that match for the numbers vs. the /, so it expects for instance "1 / 2"  not "1/2". 

b) supposing your string does have a fraction with spaces in it like "1 / 2" your replacement basically just swaps out the "/" for a "|"...which..why? You said you wanted to mark it up with some html strong...

 

@QuickOldCar: couple things about your regex..

 

a) since you are matching for a / it would be cleaner to pick a different pattern delimiter so you don't have to escape it in the pattern.

b)  [..] is a character class. It means to match any one thing inside the bracket. It is good for if you want to match for more than 1 thing like something in a range.  For example [a-z0-9] will match any 1 letter or number.  Since you are only matching for one thing (a "/"), while it *technically* works, there's no need for a character class.

c) Your pattern will only match single-digit fractions.  For instance, it will not match 1/10 (it will only match 1/1 part of it).

 

@shamuraq:

 

Here is a pattern for you:

 

$pattern = '~([0-9]+\s?+/\s?[0-9]+)~';

 

This will capture the entire fraction  $1 or \1 for your $replacement variable.  This pattern will allow for both "1/2" and "1 / 2".  If you only want it to match if no spaces, remove the two "\s?" parts.

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/254536-preg-replace-help/#findComment-1305669
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.