I know this was answered a long time ago, but I had the same issue and none of the answer would be what I call "plug and use". The answers are correct, but they are not easily programmable. So here is my "plug in" solution allowing a 2 line algorithm. Sorry if the format is bad but I don't know how to do fancy equations.
For the base, I used the above answers and this video: https://www.youtube.com/watch?v=0lG53-ogF2k
Giving:
p1 any point on the line
a a vector representing the line
p0 any point in the world
t a scalar
pt the closest point on the line
The goal is to find the point pt where the vector p0pt is perpendicular from the line, represented by the a vector. This gives the following:
a ᵒ p0x = 0
== Definition of a vector
(a.x, a.y, a.z) ᵒ (pt.x - p0.x, pt.y - p0.y, pt.z - p0.z) = 0
== Definition of scalar product
a.x * (pt.x - p0.x) + a.y * (pt.y - p0.y) + a.z * (pt.z - p0.z) = 0
== We know that pt is on the line and must respect pt = p1 + t * a
a.x * (p1.x + t * a.x - p0.x) + a.y * (p1.y + t * a.y - p0.y) + a.z * (p1.z + t * a.z - p0.z) = 0
== We pull the t parts from the parenthesis
t * a.x * a.x + a.x * (p1.x - p0.x) + t * a.y * a.y + a.y * (p1.y - p0.y) + t * a.z * a.z + a.z * (p1.z - p0.z) = 0
== We send all non t related values to the right side of the equation
t * a.x * a.x + t * a.y * a.y + t * a.z * a.z = - a.x * (p1.x - p0.x) - a.y * (p1.y - p0.y) - a.z * (p1.z - p0.z)
== We regroup the t
t * (a.x * a.x + a.y * a.y + a.z * a.z) = - a.x * (p1.x - p0.x) - a.y * (p1.y - p0.y) - a.z * (p1.z - p0.z)
== We isolate t
t = (- a.x * (p1.x - p0.x) - a.y * (p1.y - p0.y) - a.z * (p1.z - p0.z)) / (a.x * a.x + a.y * a.y + a.z * a.z)
Now all you have to do is enter the values in the last formula and you will have your t, allowing to find your point pt by plugging it in the p1 + t * a formula.
In the case of the original poster, and using the answer from Brandon Carter, we can define the line as:
p1 = (-2, -4, 5)
a = ( 1, 2, -2)
p0 = ( 1, 1, 1)
If we plug the numbers in the formula:
t = (-1 * (-2 - 1) - 2 * (-4 - 1) - -2 * (5 - 1)) / (1 * 1 + 2 * 2 + -2 * -2)
t = (3 + 10 + 8)/(1+4+4)
t = 21/9
t = 7/3
pt = (-2, -4, 5) + 7/3 * ( 1, 2, -2)
pt = (1/3, 2/3, 1/3)