Hello, I am struggling with this. I am trying to grab something that is between two words and replace the entire string all these words come from with just the one thing that I matched. I know I am doing something wrong but I don't know enough about RegEx to figure it out. I have this: $string = 'words and words'; // $desired_output = 'and'; $desired_output = preg_replace('/words(.+)words/','$1',$string); can I get a nudge in the right direction please? Thanks
I basically want to set two delimiting words and grab ONLY what is between those words and throw out everything else there is before and after what I grabbed, you know what I mean?
<?php $string = 'words and words'; preg_match('/words(?:\s+)?(?P<output>.*)(?:\s+)?words/', $string, $matches); list(, $output) = array_map('trim', $matches); echo $output; PHP:
I figured out why it wasn't working. I was doing (.+) but instead it had to be (.+?) Thanks for all your help! You are right. I did that.
.+? makes the quantifier non-greedy (although more accurately, opposite of current behaviour as it can be toggled with a flag - but who cares about that). My solution worked fine, perhaps another part of your code wasn't ideal? Dan.
I wasn't implying that your solution wasn't working, I just found that with the question mark my code worked and only after that I read your post... I didn't try your code because I was following the "if it ain't broken don't fix it" philosophy ;-)
I wasn't implying that your solution wasn't working, I just found that with the question mark my code worked and only after that I read your post... I didn't try your code because I was following the "if it ain't broken don't fix it" philosophy ;-)