0

I want to replace this string The first word 1/4W may be different The character W it may be an upper case or a lower case

<?php
$str="1/4W this is string"; // 1/4W can be 1/16W, 1/2W, 1W,2w
$str=preg_replace(("/^\d.W/", "", $str);
var_dump($str);

I have tested but I think it is not exact

1 Answer 1

2

Use this regex: ^\d+(?:/\d+)?w

$str="1/4W this is string"; // 1/4W can be 1/16W, 1/2W, 1W,2w
$str=preg_replace(("~^\d+(?:/\d+)?w~i", "", $str);

Explanation:

~       : regex delimiter
  ^     : start of string
  \d+   : 1 or more digits
  (?:   : start non capture group
    /   : a slash
    \d+ : 1 or more digits
  )?    : end group, optional
  w     : w
~i      : regex delimiter, case insensitive
Sign up to request clarification or add additional context in comments.

5 Comments

in the result i have à space in the begin of string i can use trim to remove this space but can you remove space by regex
i have add \s to the regex "~^\d+(?:/\d+)?w\s~i" is correct?
@user8247367: Yes, just add \s at the end.
@user8247367: see my answer for other question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.