开发者

need help with Preg_replace Regular expressions

开发者 https://www.devze.com 2022-12-20 10:11 出处:网络
these word1 and word2 is in brackets want to remove the whole line depends on word2 [word1] something-line-text [word2] some text again

these word1 and word2 is in brackets

want to remove the whole line depends on word2

[word1] something-line-text [word2] some text again

want to replace some text with another depends on word2

[word1] something-line-text [word2] some text again

into

REPLCACEDTEXT somet开发者_如何学编程hing-line-text some text again

some line text (something/something)

into

(something/something) some line text


I'm not 100% sure what you want, but this will look for [word1] and [word2] and remove them only if both are on the line:

$line = preg_replace('/word1(.*)word2/', '$1', $line);

This method could match on partial words, and you could be left with extra whitespace. Slightly better would be:

$line = preg_replace('/\s?word1\b(.*)\s?word2\b/', '$1', $line);

This makes sure that they are matched as whole words using word boundaries and spaces. I use spaces on one side so that the extra space is consumed. If you don't care about that just use \b on both sides of each word.

Second case, moves the first parenthesized phrase to the beginning of the line:

$line = preg_replace('/(.*)(\(.*?\))/', '$2 $1', $line);

Edit:

After seeing your example, I think you want:

$line = preg_replace('/^\[Scene\].*/', '', $line);

$line = preg_replace('/\[\.*?\]\s+(.*)(\[.*?\])/', '$2 $1');

$line = preg_replace('/(.*)\s+(\(.*?\))/', '$2 $1');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号