How to get last name first inital [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Regex - Return First and Last Name
Hi,
I have the full name of users stored in one field. How can i get the full first name and last name first initial. This is what i am using right now:
$first = substr($full_n, 0, strpos($full_n,' '));

list ($first, $last) = explode(' ', $full_n, 2);
echo "$first {$last[0]}.";
Will not work with more than two names too, like all the other solutions. You should save all (firstname, middle name, surname, ...) separatly, if you want to do more with it, than just displaying.
Update:
Inspired be Pekka (comments of the question ;))
$names = explode(' ', $full_n);
$first = array_shift($names);
$last = array_pop($names);
echo "$first {$last[0]}.";
This works for an arbitrary (>= 2) count of names, but will only display the first (complete) and the last (shortened). Something like "Schmidt-Mueller" will look curious ("S.").

Well, you're almost there...
If it's guaranteed that your users will have two names (just first and last, with no spaces in either), then you could just do this:
$full_n = 'Demian Brecht';
$first = substr($full_n, 0, strpos($full_n,' ')+2);
print_r($first);
However, if you're dealing with > 2 names, then you'll have to rethink your logic.

(not an answer but too big to be a comment)
There is no solution to this problem, you will just have to decide in what way will you mangle peoples names.
There are several decent examples in the answers already, but they will all fail on Pekka's examples in his comment. Some names like Hillary Rodham Clinton are often hyphenated Hillary Rodham-Clinton and will be less of a problem.
Simpler common examples such as John von Neumann or Phillip de la Cruz will still fail.

$full_n = trim($full_n); // remove extra spaces
$first_name = substr($full_n, 0, strpos($full_n, ' '));
$last_initial = substr($full_n, strrchr($full_n, ' '), 1);
$result = trim($first_name . ' ' . $last_initial);

I had a hard time understanding this question. If you want the full first name and the first initial of the last name.
$firstwithlastnameinitial = substr($full_n, 0, strpos($full_n, ' ')) . substr($full_n, strpos($full_n, ' ') + 1, 1);
OR
list ($fname, $lname) = explode(' ', $full_n, 2);
$lastwithfirstinitial = $fname . substr($lname, 0, 1);
If you want the full last name with first initial of the first name:
$lastwithfirstinitial = substr($full_n, strpos($full_n, ' ') + 1, strlen($full_n)) . substr($full_n, 0, 1);
This should retrieve the last name plus the first initial. Or something easier to read.
list ($fname, $lname) = explode(' ', $full_n, 2);
$lastwithfirstinitial = $lname . substr($fname, 0, 1);

Related

Parsing a mixed-delimiter data set

I've got a source file that contains some data in a few formats that I need to parse. I'm writing an ETL process that will have to match other data.
Most of the data is in the format city, state (US standard, more or less). Some cities are grouped across heavier population areas with multiple cities combined.
Most of the data looks like this (call this 1):
Elkhart, IN
Some places have multiple cities, delimited by a dash (call this 2):
Hickory-Lenoir-Morganton, NC
It's still not too complicated when the cities are in different states (call this 3):
Steubenville, OH-Weirton, WV
This one threw me for a loop; it makes sense but it flushes the previous formats (call this 4):
Kingsport, TN-Johnson City, TN-Bristol, VA-TN
In that example, Bristol is in both VA and TN. Then there's this (call this 5):
Mayagüez/Aguadilla-Ponce, PR
I'm okay with replacing the slash with a dash and processing the same as a previous example. That contains a diacritic as well and the rest of my data are diacritic-free. I'm okay with stripping the diacritic off, that seems to be somewhat straightforward in PHP.
Then there's my final example (call this 6):
Scranton--Wilkes-Barre--Hazleton, PA
The city name contains a dash so the delimiter between city names is a double dash.
What I'd like to produce is, given any of the above examples and a few hundred other lines that follow the same format, an array of [[city, state],...] for each so I can turn them into SQL. For example, parsing 4 would yield:
[
['Kingsport', 'TN'],
['Johnson City', 'TN'],
['Bristol', 'VA'],
['Bristol', 'TN']
]
I'm using a standard PHP install, I've got preg_match and so on but no PECL libraries. Order is unimportant.
Any thoughts on a good way to do this without a big pile of if-then statements?
I would split the input with '-'s and ','s, then delete empty elements in the array. str_replace followed by explode and array_diff (, array ()) should do the trick.
Then identify States - either searching a list or working on the principal that cities don't tend to have 2 upper-case letter names.
Now work through the array. If it's a city, save the name, if it's a state, apply it to the saved cities. Clear the list of cities when you get a city immediately following a state.
Note any exceptions and reformat by hand into a different input.
Hope this helps.
For anyone who's interested, I took the answer from #mike and came up with this:
function SplitLine($line) {
// This is over-simplified, just to cover the given case.
$line = str_replace('ü', 'u', $line);
// Cover case 6.
$delimiter = '-';
if (false !== strpos($line, '--'))
$delimiter = '--';
$line = str_replace('/', $delimiter, $line);
// Case 5 looks like case 2 now.
$parts = explode($delimiter, $line);
$table = array_map(function($part) { return array_map('trim', explode(',', $part)); }, $parts);
// At this point, table contains a grid with missing values.
for ($i = 0; $i < count($table); $i++) {
$row = $table[$i];
// Trivial case (case 1 and 3), go on.
if (2 == count($row))
continue;
if (preg_match('/^[A-Z]{2}$/', $row[0])) {
// Missing city; seek backwards.
$find = $i;
while (2 != count($table[$find]))
$find--;
$table[$i] = [$table[$find][0], $row[0]];
} else {
// Missing state; seek forwards.
$find = $i;
while (2 != count($table[$find]))
$find++;
$table[$i][] = $table[$find][1];
}
}
return $table;
}
It's not pretty and it's slow. It does cover all my cases and since I'm doing an ETL process the speed isn't paramount. There's also no error detection, which works in my particular case.

Adding links to a PHP array list?

I never intended to have to use PHP - heck, two days ago I didn't even know what it was, so excuse me if any of my terminology is weird or incorrect.
My predicament is that I need a working code that will end up outputting a list of writer names (that's why the array is called "writers") that are linked to their writer pages/profiles. Here's what I have so far that correctly displays the list of writer names:
<?php
$writers = get_post_meta($post->ID, 'writer', false);
$last = array_slice($writers, -1);
$first = join(', ', array_slice($writers, 0, -1));
$both = array_filter(array_merge(array($writers), $last), 'strlen');
echo join(' and ', $both);
?>
And the correct writer page link can be generated with this code:
<?php echo get_post_meta($post->ID, 'writerlink', true); ?>
I just don't have the skill to get these puzzle pieces to fit together. Since there are often multiple writers, there will often be more than one writer link. Is it possible to have each list/array value to have its correct link attached?

How to replace some character in mysql column by 'x'?

I have emails like this
uuak6G6GgD#gmail.com
d3lferM#gmail.com
Efqc9#gmail.com
How to convert and select like this.
uuakxxxxxx#xxxxx.xxx
d3lfxxx#xxxxx.xxx
Efqcx#xxxxx.xxx
Yes I am able to get this value but, I am not good enough in mysql function so please help me to make it simple and short if possible. And also suggest what other solution would be to make it.
I have created my query as
SELECT CONCAT(LEFT(email,
4),SUBSTR(REGEXP_REPLACE(email,'[a-z0-9]',"x"),5)),email
FROM `users`
I am using PHP as server side, so If we could involve php to make good enough, please also suggest.
Your help and suggestions are heartily appreciable.
If the point is obfuscation of email addresses, then you should not replace the characters by x, thus giving indication on the length of the email address. Just take the first 4 characters (left() function) and add a fixed ending of "xxxxxxxx#xxxx.xxx". You also need to decide how to handle email addresses where the user part is shorter than 4 characters.
If you want to achieve this using PHP you can simply use the following regex along with preg_replace function like as
(^(\w){1,4}|#|\.)(*SKIP)(*F)|(.)
Example :
echo preg_replace("/(^(\w){1,4}|#|\.)(*SKIP)(*F)|(.)/","$1x","uuak6G6GgD#gmail.com");
I would suggest something like :
$email = substr($email, 0, 4) . preg_replace('/\w/', 'x', substr($email, 4));
Doing it in the MySQL query is usually not reasonnable imo. MySQL isn't very good at that kind of data transformation.
$emails = [
'uuak6G6GgD#gmail.com',
'd3lferMGo7#gmail.com',
'Efqc90dUGI#gmail.com',
'I#gmail.com',
];
$modded = [];
foreach ($emails as $item) {
$name = explode('#', $item);
$name = str_pad(substr($name[0], 0, 4), 4, "x");
$modded[] = $name . 'xxxx#xxx.xxx';
}
var_dump($modded);
involve php, select record and than
Break every email address in two parts
$email = 'I#gmail.com';
$email = explode('#', $email);
$firstPart = $email[0];
$lastPart = $email[1];
$first4 = substr($firstPart, 0, 4);
$mid = preg_replace('/[^.#\-]/', 'x', substr($firstPart, 4));
$last = preg_replace('/[^.#\-]/', 'x', $lastPart);
$converted = $first4.$mid.'#'.$last;

replacing all x numbers except last 4 within input value

I have an input that looks like this
<input value="{{gameAccount.getAccountNumber() }}" disabled name="accountNumber" type="text">
which displays:
123456789
but I want it to display
*****6789
I get confused when it is in input value in this particular case with gameAccount.getAccountNumber()
substr($something?, 0, -4) . '****';
How do I go about this? thanks in advance
I also saw substr_replace() function...
As #ficuscr points out this is a better one liner for this:
$gameId = '123456789';
$gameId = str_repeat('*', strlen($gameId) - 4) . substr($gameId, -4);
There may be a more elegant way to do this but this will work:
$gameId = '123456789';
$gameIdLenToMask = strlen($gameId) - 4;
$mask = str_pad('', $gameIdLenToMask, '*');
$gameIdMasked = substr_replace($gameId, $mask, 0, $gameIdLenToMask);
// Prints: "*****6789"
var_dump($gameIdMasked);
For more information see the docs for str_replace and str_pad on php.net.
One other option, you can use the length minus four as the limit argument for preg_replace.
$new = preg_replace('/./', '*', $str, strlen($str) - 4);
If you aren't sure that your string will be at least four characters, you can use max to be sure the limit doesn't go negative.
$new = preg_replace('/./', '*', $str, max(0, strlen($str) - 4));

Splitting strings through php to query mysql

I need to split a string in two so I can do a SELECT query in my DB. For example, I have the number '0801'. I need to split that number into '08' and '01'. How do I manage to do that?
This is easy to do using the substr() function, which lets you pull out parts of a string. Given your comment that you always have a four-digit number and want it split into two two-digit numbers, you want this:
$input = "0801";
$left = substr($input, 0, 2);
$right = substr($input, 2);
echo "Left is $left and right is $right\n";
According to your comment
The first 2 numbers. It's allways a 4 digit number and I allways need
to split it in 2 two digit numbers
You can simply use
$value = '0801';
$split = str_split($value, 2);
var_dump($split[0]);
var_dump($split[1]);
Just keep in mind $value variable should always be of a string type, not int.
you can use str_split and list
$str = '0801';
list($first,$second) = str_split($str,2);
echo $first;
// 08
echo $second;
// 01
No one gave a MySQL answer yet...
If you're selecting that number..
SELECT
SUBSTR(colname, 0, 2) as firstpart,
SUBSTR(colname, 2, 2) as secondpart
FROM table

Categories