Reputation: 125
I have found a solution on how to cut a text by using regex.
^(?=((?:.*?\S){40})) // GET FIRST 40 CHARACTERS (IGNORING SPACES)
Fron: Extract n-character substring while ignoring spaces
The problem is if I entered this: asdgfhtjshhhhhhhhhasdasdasdass asd
, nothing has been extracted.
Here is the regex101 link: https://regex101.com/r/fM9lY3/5#javascript
Upvotes: 1
Views: 1220
Reputation: 158160
You can simply use the following regex:
^(\s*\S){1,40}
You don't need a lookahead assertion, you can simply put zero or more space characters and a non-space character into a capturing group. Then trailing quantifier will ensure it occurs up to 40 times. The key here is the optional space.
Try it: https://regex101.com/r/fM9lY3/40
Upvotes: 1
Reputation: 28850
This one makes just a small usage of regex, but it works
$x = "asdgfhtjshhhhhhhhhasdasdasdass asd";
$result = substr(implode("", preg_split('/\s+/', $x)), 0, 40);
Upvotes: 0
Reputation: 954
This is because {40} means exactly 40, and the text you inputted has less than 40 characters. Try with {1,40} (which means from 1 to 40):
^(?=((?:.*?\S){1,40}))
Upvotes: 0