How to remove surrounding Square Brackets using php - php

I need a way to remove the surrounding square brackets from this using only php:
[txt]text[/txt]
So the result should be: text
They will always occur in matched pairs.
They always will be at the start and end of the string. Thet will always be [txt1][/txt1] or [url2][/url2]
How can i do it?

Try this:
preg_replace("/\[(\/\s*)?txt\d*\]/i", "", "[txt]text[/txt]");
Update:
This will work for "whatever" in the brackets:
preg_replace("/\[.+?\]/i", "", "[txt]text[/txt]");

You do not need to use regexp. You can explode the string on first ], after that use the result to explode on [.
Advantage using this method is that it is fast and simple.

If you simply need to get the text between square brackets of a simple structure, then try this:
$str = '[tag1]fdhfjdkf dfhjdkf[/tag1]';
$start_position = strpos($str, ']') + 1;
$end_postion = strrpos($str, '[');
$cleared = substr($str, $start_position, $end_postion - $start_position);
For more complicated structures this code won't work and you'll have to use some other ways.

You can use regex:
$string = '[whatever]content[/whatever]';
$pattern = '/\[[^\[\]]*\]/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
This will remove all [whatever] from a string.

Related

Remove excess commas from string PHP

I've filtered some keywords from a string, to remove invalid ones but now I have a lot of extra commas. How do I remove them so I go from this:
,,,,,apples,,,,,,oranges,pears,,kiwis,,
To this
apples,oranges,pears,kiwis
This question is unique because it also deals with commas at the start and end.
$string = preg_replace("/,+/", ",", $string);
basically, you use a regex looking for any bunch of commas and replace those with a single comma.
it's really a very basic regular expression. you should learn about those!
https://regex101.com/ will help with that very much.
Oh, forgot: to remove commas in front or after, use
$string = trim($string, ",");
Use PHP's explode() and array_filter() functions.
Steps:
1) Explode the string with comma.
2) You will get an array.
3) Filter it with array_filter(). This will remove blank elements from array.
4) Again, implode() the resultant array with comma.
5) You will get commas removed from the string.
<?php
$str = ',,,,,apples,,,,,,oranges,pears,,kiwis,,';
$arr = explode(',', $str);
$arr = array_filter($arr);
echo implode(',', $arr);// apples,oranges,pears,kiwis
?>
You can also achieve this by using preg_split and array_filter.
$string = ",,,,,apples,,,,,,oranges,pears,,kiwis,,";
$keywords = preg_split("/[\s,]+/", $string);
$filterd = array_filter($keywords);
echo implode(",",$filterd);
Result:
apples,oranges,pears,kiwis
Explanation:
split with comma "," into an array
use array_filter for removing empty indexes.
implode array with "," and print.
From Manual: preg_split — Split string by a regular expression (PHP 4, PHP 5, PHP 7)
How about using preg_replace and trim?
$str=',,,,,apples,,,,,,oranges,pears,,kiwis,,';
echo trim( preg_replace('#,{2,}#',',',$str), ',');

Trim string based on certain characters

I've got a string which goes something like myString__sfsdfsf
All I know is that there is a __ somewhere in the string. Content of the string and number of characters is unknown.
I want to remove the __ and all characters that follow so I am left with just myString. How can I achieve this using PHP?
This can be done in several ways. PHP has lots of string functions. You can pick one depending on your requirements. Here are some ways:
Use substr() and strpos():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__')); // => myString
Or use strtok():
echo strtok($str, '__'); // => myString
Or, maybe even explode():
echo explode('__', $str)[0]; // => myString
You can make use of strpos() and substr():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__'));
This should be quite fast. However if you need something more fancy than that, you probably want to look into regular expressions, e.g. preg_match().
Use list() and explode():
list($string,) = explode('_', 'myString__sfsdfsf');
echo $string; // Outputs: myString
A str_replace() would also work
$string = str_replace('__', '', $string);
Ignore that, didn't read your question properly

How to extract a collection of numbers from a string?

I need to extract a project number out of a string. If the project number was fixed it would have been easy, however it can be either P.XXXXX, P XXXXX or PXXXXX.
Is there a simple function like preg_match that I could use? If so, what would my regular expression be?
There is indeed - if this is part of a larger string e.g. "The project (P.12345) is nearly done", you can use:
preg_match('/P[. ]?(\d{5})/',$str,$match);
$pnumber = $match[1];
Otherwise, if the string will always just be the P.12345 string, you can use:
preg_match('/\d{5}$/',$str,$match);
$pnumber = $match[0];
Though you may prefer the more explicit match of the top example.
Try this:
if (preg_match('#P[. ]?(\d{5})#', $project_number, $matches) {
$project_version = $matches[1];
}
Debuggex Demo
You said that project number is 4 of 5 digit length, so:
preg_match('/P[. ]?(\d{4,5})/', $tring, $m);
$project_number = $m[1];
Assuming you want to extract the XXXXX from the string and XXXXX are all integers, you can use the following.
preg_replace("/[^0-9]/", "", $string);
You can use the ^ or caret character inside square brackets to negate the expression. So in this instance it will replace anything that isn't a number with nothing.
I would use this kind of regex : /.*P[ .]?(\d+).*/
Here is a few test lines :
$string = 'This is the P123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P.123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P 123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
use explode() function to split those

how to remove last occurance of underscore in string

I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;

String Manipulation in PHP

How can I get the value between the {} eg. 1 in "{1}" and use it?
if (preg_match('/\{(\d+)\}/', $str, $mtch))
echo $mtch[1];
where $str is '{1}'
If you just want to get rid of the brackets, you may use trim() function
$str = "{1}";
$str = trim($str, "{}");
echo $str; //output: 1
EDIT: I removed the comma - "{}" is enough as the secont parameter for trim() (was "{,}" before the edit)
You can use a preg_replace function to perform a regular expression.
What exactly do you need to do the string.
If you want to get a certain character of the string, $str = '{1}'; $str[1] will return the 2nd character of the string.
Depends on what you actually have .. in the example above this would be enough:
$number = $string{1};
But i guess you need more something like
preg_match('/{([0-9]+)}/', $string, $matches);
$number = $matches[1];

Categories