Domas
Domas

Reputation: 1133

PHP only leave text in between particular characters

I have many strings that look like this:

[additional-text Sample text...]

There is always an opening bracket + additional-text + single space and a closing bracket in the end and I need to remove all of them, so that the final string would look like this:

Sample text...

Any help or guidance is much appreciated.

Upvotes: 0

Views: 85

Answers (6)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

There is no need in regex, use substr:

$s = "[additional-text Sample text...]";
echo substr($s, 17, strlen($s)-18);

Where 17 is the length of [additional-text and 18 is the same + 1 for the last ].

See PHP demo

A regex solution is also basic:

^\[additional-text (.*)]$

or - if there can be no ] before the end:

^\[additional-text ([^]]*)]$

And replace with $1 backreference. See the regex demo, and here is a PHP demo:

$result = preg_replace('~^\[additional-text (.*)]$~', "$1", "[additional-text Sample text...]");
echo $result;

Pattern details:

  • ^ - start of string
  • \[ - a literal [
  • additional-text - literal text
  • (.*) - zero or more characters other than a newline as many as possible up to
  • ]$ - a ] at the end of the string.

Upvotes: 1

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

you can also do this

$a = '[additional-text Sample text...]';
$a= ltrim($a,"[additional-text ");
echo $a= rtrim($a,"]");

Upvotes: 1

Victor Radu
Victor Radu

Reputation: 2292

You can use this o get all matches within a text block:

preg_match_all("/\[additional-text (.*?)\]/",$text,$matches);

all your texts will be in $matches[1]. So that will be:

$text = "[additional-text Sample text...]dsfg fgfd[additional-text Sample text2...] foo bar adfd as ff";
preg_match_all("/\[additional-text (.*?)\]/",$str,$matches);
var_export($matches[1]);

Upvotes: 1

Ben Hillier
Ben Hillier

Reputation: 2104

Use substr to remove the first 17 characters. Use regex to remove the last two:

$val = '[additional-text Sample text...]';
$text = preg_replace('#\]$#', '', substr($val, 17));

Upvotes: 1

anubhava
anubhava

Reputation: 784958

You can use:

$re = '/\[\S+\s|\]/'; 
$str = "[additional-text Sample text...]"; 

$result = preg_replace($re, '', $str);
//=> Sample text...

RegEx Demo

Upvotes: 1

heemayl
heemayl

Reputation: 41987

Get the substring you want to keep as a captured group:

^\[\S+\s([^]]+)\]$

Now in the replacement, use the only captured group, \1.

Demo

Upvotes: 1

Related Questions