PHP Remove Value of String with Variable Numbers - php

Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?

It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.
But in the meantime, you can use rtrim() to trim all numbers off of the right side.
$val = rtrim($val, '0123456789');
Examples
Input Output
nameofproject1001 nameofproject
nameofproject nameofproject
n4me0fproj3ct1001 n4me0fproj3ct

for string like, project12V123, It is better to do this
$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);
Will return:
Project12V
or use rtrim:
$text = rtrim($text,'0123456789');

You should definitely use regular expressions:
$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";

preg_replace('/[^a-z]/i', '', $string);

Related

Manipulating a version number w/o regex?

I have a 4-digit version-number ("1234") and would like to insert "_" to separate the digits ("1_2_3_4").
The only idea I came up with was using regex:
<?
$str="1234";
$s1 = preg_replace("/\d/","$0_",$str,3);
echo "$str|$s1";
?>
But I have a nagging feeling there must be a more elegant way to achive this w/o rx, by using just the string-manipulation methods. Any suggestions?
Using your example string, you could also use str_split and implode in this case:
$str = '1234';
$newstr = implode('_', str_split($str));
echo $newstr; // 1_2_3_4

Trying to grab a string with one substring static, and one dynamic

I'm trying to find the best way to grab the dynamic substring, but replace all of the content after.
This is what I'm trying to achieve:
{table_telecommunications}
The substring {table_ is always the same, the only that varies is telecommunications}.
I want to grab the word telecommunications so I can do a search on a MySQL table and then replace {table_telecommunications} with the content returned.
I thought of making a strpos and then explode and so on.
But I guess it would be easier with regex, but I have no skills on creating regex.
Could you possibly give me the best way to do this?
Edit: I'm saying possibly regex is the best way because I need to find strings that are in this format, but the second part is variable, just like {table_*}
Use Regex.
<?php
$string = "{table_telecommunications} blabla blabla {table_block}";
preg_match_all("/\{table_(.+?)\}/is", $string, $matches);
$substrings = $matches[1];
print_r($substrings);
?>
if (preg_match('#table_([^}]+)}#', '{table_telecommunications}', $matches)){
echo $matches[1];
}
That's a regex solution. You can do the same with explode:
$parts = explode('table_', '{table_telecommunications}');
echo substr($parts[1], 0, -1);
$input = '{table_telecommunications}';
$table_name = trim(implode('_', array_shift(explode($input, '_'))), '}');
Should be fast, no regex required.

PHP get specific string from url before and after unknown characters

I know it may sound as a common question but I have difficulty understanding this process.
So I have this string:
http://domain.com/campaign/tgadv?redirect
And I need to get only the word "tgadv". But I don't know that the word is "tgadv", it could be whatever.
Also the url itself may change and become:
http://domain.com/campaign/tgadv
or
http://domain.com/campaign/tgadv/
So what I need is to create a function that will get whatever word is after campaign and before any other particular character. That's the logic..
The only certain thing is that the word will come after the word campaign/ and that any other character that will be after the word we are searching is a special one ( i.e. / or ? )
I tried understanding preg_match but really cannot get any good result from it..
Any help would be highly appreciated!
I would not use a regex for that. I would use parse_url and basename:
$bits = parse_url('http://domain.com/campaign/tgadv?redirect');
$filename = basename($bits['path']);
echo $filename;
However, if want a regex solution, use something like this:
$pattern = '~(.*)/(.*)(\?.*)~';
preg_match($pattern, 'http://domain.com/campaign/tgadv?redirect', $matches);
$filename = $matches[2];
echo $filename;
Actually, preg_match sounds like the perfect solution to this problem. I assume you are having problems with the regex?
Try something like this:
<?php
$url = "http://domain.com/campaign/tgadv/";
$pattern = "#campaign/([^/\?]+)#";
preg_match($pattern, $url, $matches);
// $matches[1] will contain tgadv.
$path = "http://domain.com/campaign/tgadv?redirect";
$url_parts = parse_url($path);
$tgadv = strrchr($url_parts['path'], '/');
You don't really need a regex to accomplish this. You can do it using stripos() and substr().
For example:
$str = '....Your string...';
$offset = stripos($str, 'campaign/');
if ( $offset === false ){
//error, end of h4 tag wasn't found
}
$offset += strlen('campaign/');
$newStr = substr($str, $offset);
At this point $newStr will have all the text after 'campaign/'.
You then just need to use a similar process to find the special character position and use substr() to strip the string you want out.
You can also just use the good old string functions in this case, no need to involve regexps.
First find the string /campaign/, then take the substring with everything after it (tgadv/asd/whatever/?redirect), then find the next / or ? after the start of the string, and everything in between will be what you need (tgadv).

Restrict text input to only allow five (5) words in PHP

I want to know how I can allow only five (5) words on text input using PHP.
I know that I can use the strlen function for character count, but I was wondering how I can do it for words.
You can try it like this:
$string = "this has way more than 5 words so we want to deny it ";
//edit: make sure only one space separates words if we want to get really robust:
//(found this regex through a search and havent tested it)
$string = preg_replace("/\\s+/", " ", $string);
//trim off beginning and end spaces;
$string = trim($string);
//get an array of the words
$wordArray = explode(" ", $string);
//get the word count
$wordCount = sizeof($wordArray);
//see if its too big
if($wordCount > 5) echo "Please make a shorter string";
should work :-)
If you do;
substr_count($_POST['your text box'], ' ');
And limit it to 4
If $input is your input string,
$wordArray = explode(' ', $input);
if (count($wordArray) > 5)
//do something; too many words
Although I honestly don't know why you'd want to do your input validation with php. If you just use javascript, you can give the user a chance to correct the input before the form submits.
Aside from all these nice solutions using explode() or substr_count(), why not simply use PHP's built-in function to count the number of words in a string. I know the function name isn't particularly intuitive for this purpose, but:
$wordCount = str_word_count($string);
would be my suggestion.
Note, this isn't necessarily quite as effective when using multibyte character sets. In that case, something like:
define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");
function str_word_count_utf8($str)
{
return preg_match_all(WORD_COUNT_MASK, $str, $matches);
}
is suggested on the str_word_count() manual page
You will have to do it twice, once using JavaScript at the client-side and then using PHP at the server-side.
In PHP, use split function to split it by space.So you will get the words in an array. Then check the length of the array.
$mytextboxcontent=$_GET["txtContent"];
$words = explode(" ", $mytextboxcontent);
$numberOfWords=count($words);
if($numberOfWords>5)
{
echo "Only 5 words allowed";
}
else
{
//do whatever you want....
}
I didn't test this.Hope this works. I don't have a PHP environment set up on my machine now.
You could count the number of spaces...
$wordCount = substr_count($input, ' ');
i think you want to do it first with Javascript to only allow the user to insert 5 words (and after validate it with PHP to avoid bad intentions)
In JS you need to count the chars as you type them and keep the count of the words you write ( by incrementing the counter each space)
Take a look of this code: http://javascript.internet.com/forms/limit-characters-and-words-entered.html

splitting strings in php

I have some testcases/strings in this format:
o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b_Testing_to_see_If_this_testcases_passes:data
rx01_01_03d_Testing_the_reconfiguration/Retest:
Actually this testcase name consists of the actual name and the description.
So, I want to split them like this :
o201_01_01a Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b Testing_to_see_If_this_testcases_passes:data
rx01_01_03d Testing_the_reconfiguration/Retest:
I am unable to figure out the exact way to do this in explode in php
Can anyone help please?
Thanks.
If the first part has always the same length, why don't you use substr, e.g.
$string = "o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data";
$first_part = substr($string, 0, 11); // o201_01_01a
$second_part = substr($string, 12); // Testing_to_see_If_this_testcases_passes:without_data
$results = preg_split("/([a-z0-9]+_[0-9]+_[0-9]+[a-z])(.*)/", $input);
That should give you an array of results, provided I got the regular expression correct.
http://www.php.net/manual/en/function.preg-split.php
Looking at the pattern, it appears that you need to use regular expressions. If this is how they all are, you can cut off the beginning by looking for an upper case character. The code might look like this:
$matches = array()
preg_match('/^[^A-Z]*?/', $string, $matches);
$matches = substr($matches[0], 0, count($matches[0])-1);
Would put the first little part into $matches. Working on second part...

Categories